diff --git a/pgsql/pgAdmin 4/docs/en_US/html/.buildinfo b/pgsql/pgAdmin 4/docs/en_US/html/.buildinfo new file mode 100644 index 0000000000000000000000000000000000000000..a32f864144dd12dd60726cb5145da77d7be59d14 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: b3c83bf398e7d0c10e7e3d8887ae2e8a +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/pgsql/pgAdmin 4/docs/en_US/html/add_restore_point_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/add_restore_point_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..1deecfd13e9e9cfdae94899a3eab725bd818bc5a --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/add_restore_point_dialog.html @@ -0,0 +1,146 @@ + + + + + + + + + + Add Named Restore Point Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Add Named Restore Point Dialog

+

Use the Add named restore point dialog to take a named snapshot of the state +of the server for use in a recovery file. To create a named restore point, the +server’s postgresql.conf file must specify a wal_level value of replica, +logical, or minimal. You must be a database superuser to create a +restore point.

+Restore point dialog +

When the Restore point name window launches, use the field Enter the name of +the restore point to add to provide a descriptive name for the restore point.

+

For more information about using a restore point as a recovery target, please +see the +PostgreSQL documentation.

+
    +
  • Click the OK button to save the restore point.

  • +
  • Click the Cancel button to exit without saving work.

  • +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/backup_and_restore.html b/pgsql/pgAdmin 4/docs/en_US/html/backup_and_restore.html new file mode 100644 index 0000000000000000000000000000000000000000..308e8df10d91446d864f7a32f810b31e406d424b --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/backup_and_restore.html @@ -0,0 +1,138 @@ + + + + + + + + + + Backup and Restore — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Backup and Restore

+

A powerful, but user-friendly Backup and Restore tool provides an easy way to +use pg_dump, pg_dumpall, and pg_restore to take backups and create copies of +databases or database objects for use in a development environment.

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/backup_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/backup_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..63fc9dda5005b224586d950b310364e2b6caa66e --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/backup_dialog.html @@ -0,0 +1,384 @@ + + + + + + + + + + Backup Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Backup Dialog

+

pgAdmin uses the pg_dump utility to provide an easy way to create a backup +in a plain-text or archived format. You can then use a client application (like +psql or the Query Tool) to restore a plain-text backup file, or use the +Postgres pg_restore utility to restore an archived backup. The pg_dump +utility must have read access to all database objects that you want to back up.

+

You can backup a single table, a schema, or a complete database. Select the name +of the backup source in the pgAdmin tree control, right click to open the +context menu, and select Backup… to open the Backup dialog. The name of +the object selected will appear in the dialog title bar.

+Backup dialog general tab +

Use the fields in the General tab to specify parameters for the backup:

+
    +
  • Enter the name of the backup file in the Filename field. Optionally, select +the Browser icon (…) to the right to navigate into a directory and select +a file that will contain the archive.

  • +
  • Use the drop-down listbox in the Format field to select the format that is +best suited for your application. Each format has advantages and +disadvantages:

    +
    +
      +
    • Select Custom to create a custom archive file that you can use with +pg_restore to create a copy of a database. Custom archive file formats +must be restored with pg_restore. This format offers the opportunity to +select which database objects to restore from the backup file. Custom +archive format is recommended for medium to large databases as it is +compressed by default.

    • +
    • Select Tar to generate a tar archive file that you can restore with +pg_restore. The tar format does not support compression.

    • +
    • Select Plain to create a plain-text script file. A plain-text script file +contains SQL statements and commands that you can execute at the psql +command line to recreate the database objects and load the table data. A +plain-text backup file can be edited in a text editor, if desired, before +using the psql program to restore database objects. Plain format is +normally recommended for smaller databases; script dumps are not +recommended for blobs. The SQL commands within the script will reconstruct +the database to the last saved state of the database. A plain-text script +can be used to reconstruct the database on another machine, or (with +modifications) on other architectures.

    • +
    • Select Directory to generate a directory-format archive suitable for use +with pg_restore. This file format creates a directory with one file for +each table and blob being dumped, plus a Table of Contents file +describing the dumped objects in a machine-readable format that +pg_restore can read. This format is compressed by default.

    • +
    +
    +
  • +
  • Use the Compression Ratio field to select a compression level for the +backup. Specify a value of zero to mean use no compression; specify a maximum +compression value of 9. Please note that tar archives do not support +compression.

  • +
  • Use the Encoding drop-down listbox to select the character encoding method +that should be used for the archive.

  • +
  • Use the Number of Jobs field (when applicable) to specify the number of +tables that will be dumped simultaneously in a parallel backup.

  • +
  • Use the dropdown listbox next to Rolename to specify the role that owns the +backup.

  • +
+

Click the Data Options tab to continue. Use the fields in the Data Options +tab to provide options related to data or pgAdmin objects that correspond to pg_dump.

+Sections option on backup dialog +
    +
  • Move switches in the Sections field box to select a portion of the object +that will be backed up.

    +
    +
      +
    • Move the switch next to Pre-data towards right position to include all +data definition items not included in the data or post-data item lists.

    • +
    • Move the switch next to Data towards right position to backup actual table +data, large-object contents, and sequence values.

    • +
    • Move the switch next to Post-data towards right position to include +definitions of indexes, triggers, rules, and constraints other than +validated check constraints.

    • +
    +
    +
  • +
+Type of objects option on backup dialog +
    +
  • Move switches in the Type of objects field box to specify details about +the type of objects that will be backed up.

    +
    +
      +
    • Move the switch next to Only data towards right position to limit the back +up to data.

    • +
    • Move the switch next to Only schemas to limit the back up to schema-level +database objects.

    • +
    • Move the switch next to Blobs towards left position to exclude large +objects in the backup.

    • +
    +
    +
  • +
+Do not save option on backup dialog +
    +
  • Move switches in the Do not save field box to select the objects that will +not be included in the backup.

    +
    +
      +
    • Move the switch next to Owner towards right position to exclude commands +that set object ownership.

    • +
    • Move the switch next to Privileges towards right position to exclude +commands that create access privileges.

    • +
    • Move the switch next to Tablespaces towards right position to exclude +tablespaces.

    • +
    • Move the switch next to Unlogged table data towards right position to +exclude the contents of unlogged tables.

    • +
    • Move the switch next to Comments towards right position to exclude +commands that set the comments. Note: This option is visible only for +database server greater than or equal to 11.

    • +
    • Move the switch next to Publications towards right position to exclude +publications.

    • +
    • Move the switch next to Subscriptions towards right position to exclude +subscriptions.

    • +
    • Move the switch next to Security labels towards right position to exclude +Security labels.

    • +
    • Move the switch next to Toast compressions towards right position to exclude +Toast compressions. Note: This option is visible only for +database server greater than or equal to 14.

    • +
    • Move the switch next to Table access methods towards right position to exclude +Table access methods. Note: This option is visible only for +database server greater than or equal to 15.

    • +
    +
    +
  • +
+Queries option on backup dialog +

Click the Query Options tab to continue. Use these additional fields to specify +the type of statements that should be included in the backup.

+
+
    +
  • Move the switch next to Use INSERT commands towards right position to +dump the data in the form of INSERT statements rather than using a COPY +command. Please note: this may make restoration from backup slow.

  • +
  • Use the Maximum rows per INSERT command field to controls the maximum +number of rows per INSERT command. Note: This option is visible only for +database server greater than or equal to 12.

  • +
  • Move the switch next to On conflict do nothing to INSERT command towards +right position to add ON CONFLICT DO NOTHING to INSERT command. +This option is not valid unless Use INSERT commands, Use Column INSERTS +or Maximum rows per INSERT command is also specified. +Note: This option is visible only for database server greater than or +equal to 12.

  • +
  • Move the switch next to Include CREATE DATABASE statement towards right +position to include a command in the backup that creates a new database +when restoring the backup.

  • +
  • Move the switch next to Include DROP DATABASE statement towards right +position to include a command in the backup that will drop any existing +database object with the same name before recreating the object during a +backup.

  • +
  • Move the switch next to Include IF EXISTS clause towards right +position to add an IF EXISTS clause to drop databases and other objects. +This option is not valid unless Include DROP DATABASE statement is also set.

  • +
+
+Backup dialog tables section +

Click the Table Options tab to continue. Use the fields in the Table Options +tab related to tables that should be included in the backup.

+
+
    +
  • Move the switch next to Use Column INSERTS towards right position to dump +the data in the form of INSERT statements and include explicit column +names. Please note: this may make restoration from backup slow.

  • +
  • Move the switch next to Load via partition root towards right position, +so when dumping a COPY or INSERT statement for a partitioned table, target +the root of the partitioning hierarchy which contains it rather than the +partition itself. Note: This option is visible only for database server +greater than or equal to 11.

  • +
  • Move the switch next to Enable row security towards right position to +set row_security to on instead, allowing the user to dump the parts of the +contents of the table that they have access to. This option is relevant +only when dumping the contents of a table which has row security.

  • +
  • Use the Include table(s) and Children field to dump the tables and any partitions +or inheritance child tables of the tables matching the pattern. +Note: This option is visible only for database server greater than or +equal to 16.

  • +
  • The Exclude patterns field is utilized to exclude patterns in the following manner:

  • +
  • Use the Table(s) field to not dump the tables matching the +pattern. Multiple patterns can be given separated by space.

  • +
  • Use the Table(s) data field to not dump data for any tables +matching the pattern. Multiple patterns can be given separated by +spaces.

  • +
  • Use the Table(s) and children field to not dump the tables and any +partitions or inheritance child tables of the tables matching the pattern. +Note: This option is visible only for database server greater than or +equal to 16.

  • +
  • Use the Table(s) data and children field to not dump data for the +tables and any partitions or inheritance child tables of the tables matching +the table pattern. Note: This option is visible only for database server +greater than or equal to 16.

  • +
+
+

Click the Options tab to continue. Use the fields in the Options +tab to provide other backup options.

+Disable option on backup dialog +
    +
  • Move switches in the Disable field box to specify the type of statements +that should be excluded from the backup.

    +
    +
      +
    • Move the switch next to Triggers (active when creating a data-only backup) +towards right position to include commands that will disable triggers on the +target table while the data is being loaded.

    • +
    • Move the switch next to $ quoting towards right position to enable dollar +quoting within function bodies; if disabled, the function body will be +quoted using SQL standard string syntax.

    • +
    +
    +
  • +
+Miscellaneous option on backup dialog +
    +
  • Move switches in the Miscellaneous field box to specify miscellaneous +backup options.

    +
    +
      +
    • Move the switch next to Verbose messages towards left position to instruct +pg_dump to exclude verbose messages.

    • +
    • Move the switch next to Force double quotes on identifiers towards right +position to force the quoting of all identifiers.

    • +
    • Move the switch next to Use SET SESSION AUTHORIZATION towards right +position to include a statement that will use a SET SESSION AUTHORIZATION +command to determine object ownership (instead of an ALTER OWNER command).

    • +
    • Use the Exclude schema field to not dump schemas whose name matches +pattern.

    • +
    • Use the Extra float digits field to use the specified value when dumping +floating-point data, instead of the maximum available precision.

    • +
    • Use the Lock wait timeout field to do not wait forever to acquire shared +table locks at the beginning of the dump. Instead, fail if unable to lock a +table within the specified timeout.

    • +
    +
    +
  • +
+

Click the Objects tab to continue.

+Select objects in backup dialog +
    +
  • +
    Select the objects from tree to take backup of selected objects only.
      +
    • If Schema is selected then it will take the backup of that selected schema only.

    • +
    • If any Table, View, Materialized View, Sequences, or Foreign Table is selected then it will take the backup of those selected objects.

    • +
    +
    +
    +
  • +
+

When you’ve specified the details that will be incorporated into the pg_dump +command:

+
    +
  • Click the Backup button to build and execute a command that builds a backup +based on your selections on the Backup dialog.

  • +
  • Click the Cancel button to exit without saving work.

  • +
+

pgAdmin will run the backup process in background. You can view all the background +process with there running status and logs on the Processes +tab

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/backup_globals_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/backup_globals_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..9c007ac9d95d8adaad4cfe6e61951b39fb65ae03 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/backup_globals_dialog.html @@ -0,0 +1,157 @@ + + + + + + + + + + Backup Globals Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Backup Globals Dialog

+

Use the Backup Globals dialog to create a plain-text script that recreates all +of the database objects within a cluster, and the global objects that are shared +by those databases. Global objects include tablespaces, roles, and object +properties. You can use the pgAdmin Query Tool to play back a plain-text +script, and recreate the objects in the backup.

+Backup globals dialog +

Use the fields in the General tab to specify the following:

+
    +
  • Enter the name of the backup file in the Filename field. Optionally, select +the Browser icon (ellipsis) to the right to navigate into a directory and +select a file that will contain the archive.

  • +
  • Use the drop-down listbox next to Role name to specify a role with +connection privileges on the selected server. The role will be used for +authentication during the backup.

  • +
+

Move switches in the Miscellaneous field box to specify the type of +statements that should be included in the backup.

+
    +
  • Move the Verbose messages switch to the No position to exclude status +messages from the backup. The default is Yes.

  • +
  • Move the Force double quote on identifiers switch to the Yes position to +name identifiers without changing case. The default is No.

  • +
+

Click the Backup button to build and execute a command based on your +selections; click the Cancel button to exit without saving work.

+

pgAdmin will run the backup process in background. You can view all the background +process with there running status and logs on the Processes +tab

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/backup_server_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/backup_server_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..d9dce50961ff4d8522ce368541830fe5c043079e --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/backup_server_dialog.html @@ -0,0 +1,292 @@ + + + + + + + + + + Backup Server Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Backup Server Dialog

+

Use the Backup Server dialog to create a plain-text script that will recreate +the selected server. You can use the pgAdmin Query Tool to play back a +plain-text script, and recreate the server.

+Backup server dialog +

Use the fields in the General tab to specify the following:

+
    +
  • Enter the name of the backup file in the Filename field. Optionally, select +the Browser icon (ellipsis) to the right to navigate into a directory and +select a file that will contain the archive.

  • +
  • Use the Encoding drop-down listbox to select the character encoding method +that should be used for the archive. Note: This option is visible only for +database server greater than or equal to 11.

  • +
  • Use the drop-down listbox next to Role name to specify a role with +connection privileges on the selected server. The role will be used for +authentication during the backup.

  • +
+

Click the Data Options tab to continue. Use the fields in the Data Options +tab to provide options related to data or pgAdmin objects that correspond to pg_dumpall.

+Type of objects option on backup server dialog +
    +
  • Move switches in the Type of objects field box to specify details about +the type of objects that will be backed up.

    +
    +
      +
    • Move the switch next to Only data towards right position to limit the back +up to data.

    • +
    • Move the switch next to Only schemas to limit the back up to schema-level +database objects.

    • +
    • Move the switch next to Only tablespaces to limit the back +up to tablespaces only.

    • +
    • Move the switch next to Only roles to limit the back up to roles only.

    • +
    +
    +
  • +
+Do not save option on backup server dialog +
    +
  • Move switches in the Do not save field box to select the objects that will +not be included in the backup.

    +
    +
      +
    • Move the switch next to Owner towards right position to exclude commands +that set object ownership.

    • +
    • Move the switch next to Role passwords towards right position to exclude +passwords for roles.

    • +
    • Move the switch next to Privileges towards right position to exclude +commands that create access privileges.

    • +
    • Move the switch next to Tablespaces towards right position to exclude +tablespaces.

    • +
    • Move the switch next to Unlogged table data towards right position to +exclude the contents of unlogged tables.

    • +
    • Move the switch next to Comments towards right position to exclude +commands that set the comments. Note: This option is visible only for +database server greater than or equal to 11.

    • +
    • Move the switch next to Publications towards right position to exclude +publications.

    • +
    • Move the switch next to Subscriptions towards right position to exclude +subscriptions.

    • +
    • Move the switch next to Security labels towards right position to exclude +Security labels.

    • +
    • Move the switch next to Toast compressions towards right position to exclude +Toast compressions. Note: This option is visible only for +database server greater than or equal to 14.

    • +
    • Move the switch next to Table access methods towards right position to exclude +Table access methods. Note: This option is visible only for +database server greater than or equal to 15.

    • +
    +
    +
  • +
+Queries option on backup server dialog +

Click the Query Options tab to continue. Use these additional fields to specify +the type of statements that should be included in the backup.

+
+
    +
  • Move the switch next to Use INSERT commands towards right position to +dump the data in the form of INSERT statements rather than using a COPY +command. Please note: this may make restoration from backup slow.

  • +
  • Use the Maximum rows per INSERT command field to controls the maximum +number of rows per INSERT command. Note: This option is visible only for +database server greater than or equal to 12.

  • +
  • Move the switch next to On conflict do nothing to INSERT command towards +right position to add ON CONFLICT DO NOTHING to INSERT command. +This option is not valid unless Use INSERT commands, Use Column INSERTS +or Maximum rows per INSERT command is also specified. +Note: This option is visible only for database server greater than or +equal to 12.

  • +
  • Move the switch next to Include DROP DATABASE statement towards right +position to include a command in the backup that will drop any existing +database object with the same name before recreating the object during a +backup.

  • +
  • Move the switch next to Include IF EXISTS clause towards right +position to add an IF EXISTS clause to drop databases and other objects. +This option is not valid unless Include DROP DATABASE statement is also set.

  • +
+
+Backup dialog tables section +

Click the Table Options tab to continue. Use the fields in the Table Options +tab related to tables that should be included in the backup.

+
+
    +
  • Move the switch next to Use Column INSERTS towards right position to dump +the data in the form of INSERT statements and include explicit column +names. Please note: this may make restoration from backup slow.

  • +
  • Move the switch next to Load via partition root towards right position, +so when dumping a COPY or INSERT statement for a partitioned table, target +the root of the partitioning hierarchy which contains it rather than the +partition itself. Note: This option is visible only for database server +greater than or equal to 11.

  • +
+
+

Click the Options tab to continue. Use the fields in the Options +tab to provide other backup options.

+Disable option on backup server dialog +
    +
  • Move switches in the Disable field box to specify the type of statements +that should be excluded from the backup.

    +
    +
      +
    • Move the switch next to Triggers (active when creating a data-only backup) +towards right position to include commands that will disable triggers on the +target table while the data is being loaded.

    • +
    • Move the switch next to $ quoting towards right position to enable dollar +quoting within function bodies; if disabled, the function body will be +quoted using SQL standard string syntax.

    • +
    +
    +
  • +
+Miscellaneous option on backup server dialog +
    +
  • Move switches in the Miscellaneous field box to specify miscellaneous +backup options.

    +
    +
      +
    • Move the switch next to Verbose messages towards left position to instruct +pg_dumpall to exclude verbose messages.

    • +
    • Move the switch next to Force double quotes on identifiers towards right +position to force the quoting of all identifiers.

    • +
    • Move the switch next to Use SET SESSION AUTHORIZATION towards right +position to include a statement that will use a SET SESSION AUTHORIZATION +command to determine object ownership (instead of an ALTER OWNER command).

    • +
    • Use the Exclude database field to not dump databases whose name matches +pattern.

    • +
    • Use the Extra float digits field to use the specified value when dumping +floating-point data, instead of the maximum available precision.

    • +
    • Use the Lock wait timeout field to do not wait forever to acquire shared +table locks at the beginning of the dump. Instead, fail if unable to lock a +table within the specified timeout.

    • +
    +
    +
  • +
+

When you’ve specified the details that will be incorporated into the pg_dumpall +command:

+
    +
  • Click the Backup button to build and execute a command that builds a backup +based on your selections on the Backup Server dialog.

  • +
  • Click the Cancel button to exit without saving work.

  • +
+

pgAdmin will run the backup process in background. You can view all the background +process with there running status and logs on the Processes +tab

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/cast_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/cast_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..2a5a161656bdccd69e1b363e8e794f33874ce48d --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/cast_dialog.html @@ -0,0 +1,197 @@ + + + + + + + + + + Cast Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Cast Dialog

+

Use the Cast dialog to define a cast. A cast specifies how to convert a value +from one data type to another.

+

The Cast dialog organizes the development of a cast through the following +dialog tabs: General and Definition. The SQL tab displays the SQL code +generated by dialog selections.

+Cast dialog general tab +

Use the fields in the General tab to identify the cast:

+
    +
  • The Name field is disabled. The name that will be displayed in the +pgAdmin tree control is the Source type concatenated with the Target +type, and is generated automatically when you make selections on the Cast +dialog Definition tab.

  • +
  • Store notes about the cast in the Comment field.

  • +
+

Click the Definition tab to continue.

+Cast dialog definition tab +

Use the fields in the Definition tab to define parameters:

+
    +
  • Use the drop-down listbox next to Source type to select the name of the +source data type of the cast.

  • +
  • Use the drop-down listbox next to Target type to select the name of the +target data type of the cast.

  • +
  • Use the drop-down listbox next to Function to select the function used to +perform the cast. The function’s result data type must match the target type +of the cast.

  • +
  • Select Context toggle to Implicit if the cast is implicit. +By default, a cast can be invoked only by an explicit cast request. If the +cast is marked Implicit then it can be invoked implicitly in any context, +whether by assignment or internally in an expression.

  • +
+

Click the SQL tab to continue.

+

Your entries in the Cast dialog generate a SQL command (see an example below). +Use the SQL tab for review; revisit or switch tabs to make any changes to the +SQL command.

+

Example

+

The following is an example of the sql command generated by user selections in +the Cast dialog:

+Cast dialog sql tab +
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/change_ownership.html b/pgsql/pgAdmin 4/docs/en_US/html/change_ownership.html new file mode 100644 index 0000000000000000000000000000000000000000..e507ce53e260593845c9d7116d28f11901be2514 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/change_ownership.html @@ -0,0 +1,155 @@ + + + + + + + + + + Change Ownership Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Change Ownership Dialog

+

Use the Change Ownership dialog to change the ownership of the shared servers. +This dialog will appear if a user has been deleted from +User Management and owned some shared servers.

+

Choose the user who will own the shared servers from the drop-down.

+Change ownership dialog +

Click the Change button to change the ownership.

+

The shared servers owned by the user will be deleted if the user is not +selected from the drop-down.

+Change ownership dialog +

Click the Change button to change the ownership; click Close to +exit the dialog.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/change_password_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/change_password_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..7765752b57817ae461bedd7f07eaf08e6f0f9c18 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/change_password_dialog.html @@ -0,0 +1,164 @@ + + + + + + + + + + Change Password Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Change Password Dialog

+

It is a good policy to routinely change your password to protect data, even in +what you may consider a ‘safe’ environment. In the workplace, failure to apply +an appropriate password policy could leave you in breach of Data Protection +laws.

+

Please consider the following guidelines when selecting a password:

+
    +
  • Ensure that your password is an adequate length; 6 characters should be the +absolute minimum number of characters in the password.

  • +
  • The minimum password length is set by default to six characters. This value +can be changed by setting the PASSWORD_LENGTH_MIN option to desired length +in pgAdmin configuration; see The config.py File for more information.

  • +
  • Ensure that your password is not open to dictionary attacks. Use a mixture of +upper and lower case letters and numerics, and avoid words or names. Consider +using the first letter from each word in a phrase that you will remember +easily but is an unfamiliar acronym.

  • +
  • Ensure that your password is changed regularly; at minimum, change it every +ninety days.

  • +
+

The guidelines above should be considered a starting point: They are not a +comprehensive list and they will not guarantee security.

+Change database password dialog +

Use the Change Password dialog to change your password:

+
    +
  • The name displayed in the User field is the role for which you are modifying +the password; it is the role that is associated with the server connection +that is highlighted in the tree control.

  • +
  • Enter the password associated with the role in the Current Password field.

  • +
  • Enter the desired password for in the New Password field.

  • +
  • Re-enter the new password in the Confirm Password field.

  • +
+

Click the Save button to change your password.

+

Click the Close button to exit without changing your password.

+

Click the Reset button to reset the values.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/change_user_password.html b/pgsql/pgAdmin 4/docs/en_US/html/change_user_password.html new file mode 100644 index 0000000000000000000000000000000000000000..348d252906f75fe6437729290ad2bf23b90551e8 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/change_user_password.html @@ -0,0 +1,173 @@ + + + + + + + + + + Change User Password Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Change User Password Dialog

+

It is a good policy to routinely change your password to protect data, even in +what you may consider a ‘safe’ environment. In the workplace, failure to apply +an appropriate password policy could leave you in breach of Data Protection +laws.

+

Please consider the following guidelines when selecting a password:

+
    +
  • Ensure that your password is an adequate length; 6 characters should be the +absolute minimum number of characters in the password.

  • +
  • The minimum password length is set by default to six characters. This value +can be changed by setting the PASSWORD_LENGTH_MIN option to desired length +in pgAdmin configuration; see The config.py File for more information.

  • +
  • Ensure that your password is not open to dictionary attacks. Use a mixture of +upper and lower case letters and numerics, and avoid words or names. Consider +using the first letter from each word in a phrase that you will remember +easily but is an unfamiliar acronym.

  • +
  • Ensure that your password is changed regularly; at minimum, change it every +ninety days.

  • +
+

The guidelines above should be considered a starting point: They are not a +comprehensive list and they will not guarantee security.

+Change current user password dialog +

Use the Change Password dialog to change your password:

+
    +
  • Enter your existing password in the Current Password field.

  • +
  • Enter the desired password for in the New Password field.

  • +
  • Re-enter the new password in the Confirm Password field.

  • +
+

Click the Change Password button to change your password; click Close to +exit the dialog.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/check_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/check_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..f962fcd12c6986fa85929b0bf39ffde8fc30e2d3 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/check_dialog.html @@ -0,0 +1,180 @@ + + + + + + + + + + Check Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Check Dialog

+

Use the Check dialog to define or modify a check constraint. A check +constraint specifies an expression that produces a Boolean result that new or +updated rows must satisfy for an insert or update operation to succeed.

+

The Check dialog organizes the development of a check constraint through the +General and Definition tabs. The SQL tab displays the SQL code generated +by dialog selections.

+Check dialog general tab +

Use the fields in the General tab to identify the check constraint:

+
    +
  • Use the Name field to provide a descriptive name for the check constraint +that will be displayed in the pgAdmin tree control. With PostgreSQL 9.5 +forward, when a table has multiple check constraints, they will be tested for +each row in alphabetical order by name and after NOT NULL constraints.

  • +
  • Store notes about the check constraint in the Comment field.

  • +
+

Click the Definition tab to continue.

+Check dialog definition tab +

Use the fields in the Definition tab to define the check constraint:

+
    +
  • Provide the expression that a row must satisfy in the Check field.

  • +
  • Move the No Inherit? switch to the Yes position to specify that this +constraint is not automatically inherited by a table’s children. The default +is No, meaning that the constraint will be inherited by any children.

  • +
  • Move the Don’t validate? switch to the No position to skip validation of +existing data; the constraint may not hold for all rows in the table. The +default is Yes.

  • +
+

Click the SQL tab to continue.

+

Your entries in the Check dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+

Example

+

The following is an example of the sql command generated by user selections in +the Check dialog:

+Check dialog sql tab +

The example shown demonstrates creating a check constraint named jobhist_date_chk +on the startdate column of the jobhist table.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/clear_saved_passwords.html b/pgsql/pgAdmin 4/docs/en_US/html/clear_saved_passwords.html new file mode 100644 index 0000000000000000000000000000000000000000..118efb1fa78efb7efcfed3d72edabeabb6ec0360 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/clear_saved_passwords.html @@ -0,0 +1,146 @@ + + + + + + + + + + Clear Saved Passwords — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Clear Saved Passwords

+

Use Clear Saved Password functionality to clear the saved password for the +database server.

+_images/clear_saved_password.png +

Clear Saved Password shows in the context menu for the selected server as well +as under the Object menu on the top menu bar.

+

Use Clear SSH Tunnel Password functionality to clear the saved password of SSH +Tunnel to connect to the database server.

+_images/clear_tunnel_password.png +

Clear SSH Tunnel Password shows in the context menu for the selected server as +well as under the Object menu on the top menu bar.

+

Note: It will be enabled/visible when the password for the selected database +server is already saved.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/cloud_aws_rds.html b/pgsql/pgAdmin 4/docs/en_US/html/cloud_aws_rds.html new file mode 100644 index 0000000000000000000000000000000000000000..b13d3536a82e5c22faebae4ad574f986c89fb704 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/cloud_aws_rds.html @@ -0,0 +1,189 @@ + + + + + + + + + + Amazon RDS Cloud Deployment — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Amazon RDS Cloud Deployment

+

To deploy a PostgreSQL server on the Amazon cloud, follow the below steps.

+Cloud Deployment Provider +

Once you launch the tool, select the Amazon RDS option. +Click on the Next button to proceed further.

+Cloud Deployment Provider +

In the Credentials dialog, provide the region in which you want to deploy the +instance along with the AWS access key and AWS secret access key. +Provide AWS session token only if your AWS session is temporary.

+

To proceed further, click on the next button. Before going further, pgAdmin +will validate your credentials.

+Cloud Deployment Provider +

Use the fields from the Instance Specification tab to specify the Instance +details.

+
    +
  • Use the Instance name field to add an instance name for the PostgreSQL +server; the name specified will be displayed in the Object Explorer too.

  • +
  • Use the Public IP field to specify the IP Address range for permitting the +inbound traffic.

  • +
  • Use the Database version field to specify the PostgreSQL version to deploy.

  • +
  • Use the Instance class field to allocate the computational, network, and +memory capacity required by planned workload of this DB instance.

  • +
  • Use the Instance type field to select the instance type.

  • +
  • Use the Storage type field to select the instance storage type. Three +options are available. General Purpose (SSD) storage, Provisioned IOPS (SSD) +and Magnetic storage.

  • +
  • Use the Allocated storage field to specify the storage capacity in GiB.

  • +
  • Use the Provisioned IOPS in case of Provisioned IOPS (SSD) storage type.

  • +
  • Use the High Availability option to specify High Availability +option. This option creates a standby in a different Availability Zone(AZ).

  • +
+Cloud Deployment Provider +

Use the fields from the Database Details tab to specify the Instance details.

+
    +
  • Use the drop-down list box in the Server group field to select the parent +node for the server; the server will be displayed in the Object Explorer +within the specified group.

  • +
  • Use the Database name field to add the database name for the PostgreSQL +server.

  • +
  • Use the Username field to specify the name of a role that will be used when +authenticating with the server.

  • +
  • Use the Password field to provide a password that will be supplied when +authenticating with the server.

  • +
  • Use the Confirm password field to repeat the password.

  • +
  • Enter the listener port number of the server host in the Port field.

  • +
+Cloud Deployment Provider +

At the end, review the Instance details that you provided. Click on Finish +button to deploy the instance on Amazon RDS.

+Cloud Deployment Provider +

Once you click on the finish, one background process will start which will +deploy the instance in the cloud and monitor the progress of the deployment. +You can view all the background process with there running status and logs +on the Processes tab

+

The Server will be added to the tree with the cloud deployment icon. Once the +deployment is done, the server details will be updated.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/cloud_azure_database.html b/pgsql/pgAdmin 4/docs/en_US/html/cloud_azure_database.html new file mode 100644 index 0000000000000000000000000000000000000000..1bb75193ac16357e2e724cabc9968ddfde914208 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/cloud_azure_database.html @@ -0,0 +1,205 @@ + + + + + + + + + + Azure Database Cloud Deployment — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Azure Database Cloud Deployment

+

To deploy a PostgreSQL server on the Azure Database, follow the below steps.

+Cloud Deployment +

Once you launch the tool, select the Azure Database option. +Click on the Next button to proceed further.

+Cloud Deployment +

In the Credentials dialog, select authentication method either interactive +browser or Azure CLI. Azure CLI will use the currently logged in identity +through the Azure CLI on the local machine. Interactive Browser will +open a browser window to authenticate a user interactively.

+

Use the Azure tenant id to specify Azure tenant ID against which user +is authenticated.

+

Clicking the Click here to authenticate yourself to Microsoft Azure +button, user will be redirected to the Microsoft Azure authentication page in a +new browser tab if the Interactive Browser option is selected. +Azure CLI authentication can be used only in Desktop mode.

+

Once authentication is completed, click on the next button to proceed.

+Cloud Deployment +

Use the fields from the Instance Specification tab to specify the Instance +details.

+
    +
  • Use the Cluster name field to add a name for the PostgreSQL +server; the name specified will be displayed in the Object Explorer too.

  • +
  • Select a subscription from the Subscription options which are populated based +on user access levels in Azure portal.

  • +
  • Select the resource group from Resource Group dropdown under which the +PostgreSQL instance will be created.

  • +
  • Select the location to deploy PostgreSQL instance from Location +options.

  • +
  • Select the availability zone in specified region to deploy PostgreSQL +instance from Availability zone options.

  • +
  • Use Database version options to specify PostgreSQL database version.

  • +
  • Use the Instance class field to allocate the computational, network, and +memory capacity required by planned workload of this DB instance.

  • +
  • Use the Instance type field to select the instance type.

  • +
  • Use the Storage size option to specify the storage capacity.

  • +
+Cloud Deployment +
    +
  • Use the Public IP field to specify the List of IP Addresses or range of +IP Addresses (start IP Address - end IP address) from which inbound traffic +should be accepted. Add multiple IP addresses/ranges separated with commas, +for example: “192.168.0.50, 192.168.0.100 - 192.168.0.200”

  • +
  • Use Zone redundant high availability option to specify High Availability +option. Zone redundant high availability deploys a standby replica in a +different zone. +The Burstable instance type does not support high availability.

  • +
+Cloud Deployment +

Use the fields from the Database Details tab to specify the PostgreSQL database details.

+
    +
  • Use the drop-down list in the pgAdmin server group field to select the parent +node for the server; the server will be displayed in the Object Explorer +within the specified group.

  • +
  • Use the Admin username field to add the database name for the PostgreSQL +server.

  • +
  • Use the Password field to provide a password that will be supplied when +authenticating with the server.

  • +
  • Use the Confirm password field to repeat the password.

  • +
+

Click on the next button to proceed.

+Cloud Deployment +

At the end, review the instance details that you provided. Click on Finish +button to deploy the instance on Azure Database.

+

Once you click on the finish, one background process will start which will +deploy the instance in the cloud and monitor the progress of the deployment. +You can view all the background process with there running status and logs +on the Processes tab

+Cloud Deployment +

The Server will be added to the tree with the cloud deployment icon. Once the +deployment is done, the server details will be updated.

+Cloud Deployment Provider +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/cloud_deployment.html b/pgsql/pgAdmin 4/docs/en_US/html/cloud_deployment.html new file mode 100644 index 0000000000000000000000000000000000000000..1f5daa806c219c90963526d8a725e2b1ffb4fa0b --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/cloud_deployment.html @@ -0,0 +1,146 @@ + + + + + + + + + + PostgreSQL Cloud Deployment — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

PostgreSQL Cloud Deployment

+

A PostgreSQL server can be deployed on the Amazon, EDB BigAnimal, Azure, +Google cloud using this module. In future more cloud provider options will +be available.

+

To launch the Cloud Deployment… tool, right click on the Server Group or +Server of the tree control, and select Deploy a Cloud Instance from the +Register menu.

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/cloud_edb_biganimal.html b/pgsql/pgAdmin 4/docs/en_US/html/cloud_edb_biganimal.html new file mode 100644 index 0000000000000000000000000000000000000000..9cd2e0d5ac34b441719759f9b4e0f140a31816ba --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/cloud_edb_biganimal.html @@ -0,0 +1,193 @@ + + + + + + + + + + EDB BigAnimal Cloud Deployment — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

EDB BigAnimal Cloud Deployment

+

To deploy a PostgreSQL server on the EDB BigAnimal cloud, follow the below steps.

+Cloud Deployment Provider +

Once you launch the tool, select the EDB BigAnimal option. +Click on the Next button to proceed further.

+Cloud Deployment Provider +

The next steps is to authenticate the user to EDB BigAninal. +Click the given button to authenticate, by clicking the button, the user +will be redirected to the new tab for the verification. +Once you confirm the one time code, the pgAdmin will automatically detect it +and the next button will be enabled. To proceed further, click on the next button.

+Cloud Deployment Provider +
    +
  • Use the Project field to choose a project in your Biganimal account.

  • +
  • Use the Cluster type field to choose a cluster type.

  • +
  • Use the No. of Standby Replicas field to specify the replicas if you have selected the High Availability cluster.

  • +
  • Use the Cluster provider field to choose the provider.

  • +
+Cloud Deployment Provider +

Use the fields from the Instance Specification tab to specify the Instance +details.

+
    +
  • Use the Cluster name field to add a cluster name for the PostgreSQL +server; the name specified will be displayed in the Object Explorer too.

  • +
  • Use the Region field to select the region.

  • +
  • Use the Public IP range field to specify the IP Address range for permitting the +inbound traffic. Leave it blank for 0.0.0.0/0

  • +
  • Use the Instance type field to select the instance type.

  • +
  • Use the Instance series field to select the instance series.

  • +
  • Use the Instance size field to allocate the computational, network, and +memory capacity required by planned workload of this DB instance.

  • +
  • Use the Volume type field to select the instance storage type.

  • +
  • Use the Volume properties field to specify the storage capacity. This field is specific to Azure.

  • +
  • Use the Volume size field to specify the storage size. This field is specific to AWS.

  • +
  • Use the Volume IOPS field to specify the storage IOPS. This field is specific to AWS.

  • +
  • Use the Disk throughput field to specify the disk throughput. This field is specific to AWS.

  • +
+Cloud Deployment Provider +

Use the fields from the Database Details tab to specify the Instance details.

+
    +
  • Use the drop-down list box in the Server group field to select the parent +node for the server; the server will be displayed in the Object Explorer +within the specified group.

  • +
  • Use the Database type field to specify the PostgreSQL +type, EnterpriseDB PostgreSQL Advanced Server or PostgreSQL.

  • +
  • Use the PostgreSQL version field to select the database version.

  • +
  • Use the Database Password field to provide a password that will be supplied when +authenticating with the server.

  • +
  • Use the Confirm password field to repeat the password.

  • +
+Cloud Deployment Provider +

At the end, review the Cluster details that you provided. Click on Finish +button to deploy the instance on EDB BigAnimal.

+Cloud Deployment Provider +

Once you click on the finish, one background process will start which will +deploy the instance in the cloud and monitor the progress of the deployment. +You can view all the background process with there running status and logs +on the Processes tab

+

The Server will be added to the tree with the cloud deployment icon. Once the +deployment is done, the server details will be updated.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/cloud_google_cloud_sql.html b/pgsql/pgAdmin 4/docs/en_US/html/cloud_google_cloud_sql.html new file mode 100644 index 0000000000000000000000000000000000000000..9b0e275e677f86850a3e82ba9d0041545b95c4a4 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/cloud_google_cloud_sql.html @@ -0,0 +1,204 @@ + + + + + + + + + + Google Cloud SQL Deployment — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Google Cloud SQL Deployment

+

To deploy a PostgreSQL server on the Google Cloud SQL, follow the below steps.

+Cloud Deployment +

Once you launch the tool, select the Google Cloud SQL option. +Click on the Next button to proceed further.

+Cloud Deployment +

In the Credentials dialog, select client secret file to authenticate +using google.You can download a client secret which is json formatted file +from google cloud console once OAuth2 client ID is created.

+
+

Note

+

While creating client OAuth client ID, select Desktop App as application type. +Refer this link for creating client secret.

+
+

Clicking the Click here to authenticate yourself to Google +button, user will be redirected to the Google authentication page in a +new browser tab.

+

Once authentication is completed, click on the next button to proceed.

+Cloud Deployment +

Use the fields from the Instance Specification tab to specify the Instance +details.

+
    +
  • Use the Cluster name field to add a name for the PostgreSQL +server; the name specified will be displayed in the Object Explorer too.

  • +
  • Select the project from project dropdown under which the +PostgreSQL instance will be created.

  • +
  • Select the location to deploy PostgreSQL instance from Location +options.

  • +
  • Select the availability zone in specified region to deploy PostgreSQL +instance from Availability zone options.

  • +
  • Use Database version options to specify PostgreSQL database version.

  • +
  • Use the Instance class field to allocate the computational and +memory capacity required by planned workload of this DB instance.

  • +
  • Use the Instance type field to select the instance type.

  • +
  • Specify storage type by selecting option from Storage type.

  • +
  • Use the Storage capacity option to specify the storage capacity.

  • +
+Cloud Deployment +
    +
  • Use the Public IP field to specify the list of IP address range +for allowed inbound traffic, for example: 127.0.0.1/32. Add multiple +IP addresses/ranges separated with commas.

  • +
  • Use the High Availability option to specify High Availability +option. This option creates a standby in a select Secondary +Availability Zone.

  • +
  • Select the secondary availability zone for high availability +from Secondary Availability zone options.

  • +
+Cloud Deployment +

Use the fields from the Database Details tab to specify the PostgreSQL database details.

+
    +
  • Use the drop-down list in the pgAdmin server group field to select the parent +node for the server; the server will be displayed in the Object Explorer +within the specified group.

  • +
  • Admin username field will be default to postgres. +server.

  • +
  • Use the Password field to provide a password that will be supplied when +authenticating with the server.

  • +
  • Use the Confirm password field to repeat the password.

  • +
+

Click on the next button to proceed.

+Cloud Deployment +

At the end, review the instance details that you provided. Click on Finish +button to deploy the instance on Azure PostgreSQL.

+

Once you click on the finish, one background process will start which will +deploy the instance in the cloud and monitor the progress of the deployment. +You can view all the background process with there running status and logs +on the Processes tab

+

The Server will be added to the tree with the cloud deployment icon. Once the +deployment is done, the server details will be updated.

+Cloud Deployment Provider +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/code_overview.html b/pgsql/pgAdmin 4/docs/en_US/html/code_overview.html new file mode 100644 index 0000000000000000000000000000000000000000..87128b60fe11afc7481a321a13d095c1b837050d --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/code_overview.html @@ -0,0 +1,343 @@ + + + + + + + + + + Code Overview — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Code Overview

+

The bulk of pgAdmin is a Python web application written using the Flask framework +on the backend, and HTML5 with CSS3,ReactJS on the front end. A +desktop runtime is also included for users that prefer a desktop application to +a web application, which is written using NWjs (Node Webkit).

+
+

Runtime

+

The runtime is based on NWjs which integrates a browser and the Python server +creating a standalone application. The source code can be found in the +/runtime directory in the source tree.

+
+
+

Web Application

+

The web application forms the bulk of pgAdmin and can be found in the /web +directory in the source tree. The main file is pgAdmin4.py which can be used +to run the built-in standalone web server, or as a WSGI application for production +use.

+
+

Configuration

+

The core application configuration is found in config.py. This file includes +all configurable settings for the application, along with descriptions of their +use. It is essential that various settings are configured prior to deployment on +a web server; these can be overridden in config_local.py or +config_system.py (see the config.py documentation) to +avoid modifying the main configuration file.

+
+
+

User Settings

+

When running in desktop mode, pgAdmin has a single, default user account that is +used for the desktop user. When running in server mode, there may be unlimited +users who are required to login prior to using the application. pgAdmin utilised +the Flask-Security module to manage application security and users, and +provides options for self-service password reset and password changes etc.

+

Whether in desktop or server mode, each user’s settings are stored in a SQLite +OR external database which is also used to store the user accounts. This is initially +created using the setup.py script which will create the database file and +schema within it, and add the first user account (with administrative +privileges) and a default server group for them. A settings table is also +used to store user configuration settings in a key-value fashion. Although not +required, setting keys (or names) are typically formatted using forward slashes +to artificially namespace values, much like the pgAdmin 3 settings files on Linux +or Mac.

+

Note that the local configuration must be setup prior to setup.py being run. +The local configuration will determine how the script sets up the database, +particularly with regard to desktop vs. server mode.

+
+
+
+

pgAdmin Core

+

The heart of pgAdmin is the pgadmin package. This contains the globally +available HTML templates used by the Jinja engine, as well as any global static +files such as images, Javascript and CSS files that are used in multiple modules.

+

The work of the package is handled in it’s constructor, __init__.py. This +is responsible for setting up logging and authentication, dynamically loading +other modules, and a few other tasks.

+
+
+

Modules

+

Units of functionality are added to pgAdmin through the addition of modules. +Theses are Python object instance of classes, inherits the +PgAdminModule class (a Flask Blueprint implementation), found in +web/pgadmin/utils.py. It provide various hook points for other modules +to utilise (primarily the default module - the browser).

+

To be recognised as a module, a Python package must be created. This must:

+
    +
  1. Be placed within the web/pgadmin/ directory, and

  2. +
  3. Implements pgadmin.utils.PgAdminModule class

  4. +
  5. An instance variable (generally - named blueprint) representing that +particular class in that package.

  6. +
+

Each module may define a template and static directory for the Blueprint +that it implements. To avoid name collisions, templates should be stored under +a directory within the specified template directory, named after the module itself. +For example, the browser module stores it’s templates in +web/pgadmin/browser/templates/browser/. This does not apply to static files +which may omit the second module name.

+

In addition to defining the Blueprint, the views module is typically +responsible for defining all the views that will be rendered in response to +client requests, we must provide a REST API url(s) for these views. These must +include appropriate route and security decorators. Take a look at the NodeView +class, which uses the same approach as Flask’s MethodView, it can be found in +web/pgadmin/browser/utils.py. This specific class is used by browser nodes +for creating REST API url(s) for different operation on them. i.e. list, create, +update, delete, fetch children, get +statistics/reversed SQL/dependencies/dependents list for that node, etc. We can +use the same class for other purpose too. You just need to inherit that class, +and overload the member variables operations, parent_ids, ids, node_type, and +then register it as node view with PgAdminModule instance.

+

Most pgAdmin modules will also implement the hooks provided by the +PgAdminModule class. This is responsible for providing hook points to integrate +the module into the rest of the application - for example, a hook might tell +the caller what CSS files need to be included on the rendered page, or what menu +options to include and what they should do. Hook points need not exist if they +are not required. It is the responsibility of the caller to ensure they are +present before attempting to utilise them.

+

Hooks currently implemented are:

+
class MyModule(PgAdminModule):
+    """
+    This is class implements the pgadmin.utils.PgAdminModule, and
+    implements the hooks
+    """
+
+    ...
+
+    def get_own_stylesheets(self):
+        """
+        Returns:
+            list: the stylesheets used by this module, not including any
+                  stylesheet needed by the submodules.
+        """
+        return [url_for('static', 'css/mymodule.css')]
+
+    def get_own_javascripts(self):
+        """
+        Returns:
+            list of dict:
+            - contains the name (representation for this javascript
+              module), path (url for it without .js suffix), deps (array of
+              dependents), exports window object by the javascript module,
+              and when (would you like to load this javascript), etc
+              information for this module, not including any script needed
+              by submodules.
+        """
+        return [
+            {
+                'name': 'pgadmin.extension.mymodule',
+                'path': url_for('static', filename='js/mymodule'),
+                'exports': None,
+                'when': 'server'
+                }
+            ]
+
+    def get_own_menuitems(self):
+        """
+        Returns:
+            dict: the menuitems for this module, not including
+                  any needed from the submodules.
+        """
+        return {
+            'help_items': [
+                MenuItem(
+                    name='mnu_mymodule_help',
+                    priority=999,
+                    # We need to create javascript, which registers itself
+                    # as module
+                    module="pgAdmin.MyModule",
+                    callback='about_show',
+                    icon='fa fa-info-circle',
+                    label=gettext('About MyModule'
+                    )
+                ]
+            }
+    def get_panels(self):
+        """
+        Returns:
+            list: a list of panel objects to add implemented in javascript
+                  module
+        """
+        return []
+    ...
+
+
+
+blueprint = MyModule('mymodule', __name__, static_url_path='/static')
+
+
+

pgAdmin Modules may include any additional Python modules that are required to +fulfill their purpose, as required. They may also reference other dynamically +loaded modules, but must use the defined hook points and fail gracefully in the +event that a particular module is not present.

+
+
+

Nodes

+

Nodes are very similar to modules, it represents an individual node or, +collection object on the object explorer treeview. To recognised as a node module, a +Python package (along with javascript modules) must be created. This must:

+
    +
  1. Be placed within the web/pgadmin/browser/ directory, and

  2. +
  3. Implements the BrowserPluginModule, and registers the node view, which +exposes required the REST APIs

  4. +
  5. An instance of the class object

  6. +
+
+
+

Front End

+

pgAdmin uses javascript extensively for the front-end implementation. It uses +require.js to allow the lazy loading (or, say load only when required), +ReactJS with CSS and MaterialUI for UI look and feel. We have +divided each module in small chunks as much as possible. Not all javascript +modules are required to be loaded (i.e. loading a javascript module for +database will make sense only when a server node is loaded completely.) Please +look at the javascript files node.js, browser.js, menu.js, panel.js, etc for +better understanding of the code.

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/code_review.html b/pgsql/pgAdmin 4/docs/en_US/html/code_review.html new file mode 100644 index 0000000000000000000000000000000000000000..672fbd184d39ca889250153bd66f7d7ee77984ea --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/code_review.html @@ -0,0 +1,177 @@ + + + + + + + + + + Code Review Notes — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Code Review Notes

+

This document lists a number of standard items that will be checked during the +review process for any changes submitted for inclusion in pgAdmin.

+
    +
  • Ensure all code follows the pgAdmin Coding Standards.

  • +
  • Ensure all code has unit test coverage and API/feature test coverage where +appropriate.

  • +
  • Copyright years must be correct and properly formatted (to make it easy to make +bulk updates every year). The start date should always be 2013, and the end year +the current year, e.g.

    +
    +

    Copyright (C) 2013 - 2024, The pgAdmin Development Team

    +
    +
  • +
  • Ensure there’s a blank line immediately following any copyright headers.

  • +
  • Include PyDoc comments for functions, classes and modules. Node modules should +be “””Implements the XXXX node”””.

  • +
  • Ensure that any generated SQL does not have any leading or trailing blank lines +and consistently uses 4 space indents for nice formatting.

  • +
  • Don’t special-case any Slony objects. pgAdmin 4 will have no direct knowledge +of Slony, unlike pgAdmin 3.

  • +
  • If you copy/paste modules, please ensure any comments are properly updated.

  • +
  • Read all comments, and ensure they make sense and provide useful commentary on +the code.

  • +
  • Ensure that field labels both use PostgreSQL parlance, but also are descriptive. +A good example is the “Init” field on an FTS Template - Init is the PG term, but +adding the word “Function” after it makes it much more descriptive.

  • +
  • Re-use code whereever possible, but factor it out into a suitably central +location - don’t copy and paste it unless modifications are required!

  • +
  • Format code nicely to make it readable. Break up logical chunks of code with +blank lines, and comment well to describe what different sections of code are +for or pertain to.

  • +
  • Ensure that form validation works correctly and is consistent with other +dialogues in the way errors are displayed.

  • +
  • On dialogues with Schema or Owner fields, pre-set the default values to the +current schema/user as appropriate. In general, if there are common or sensible +default values available, put them in the fields for the user.

  • +
  • 1 Pull Request == 1 feature. If you need to fix/update existing +infrastructure in your change, it’s usually easier if it’s in a separate +Pull Request. Pull Requests containing multiple new features or unrelated +changes are likely to be rejected.

  • +
  • Ensure the change is fully functional, and works! If you wish to send a +work in progress (WIP) change that is not intended for commit, instead of +submitting a Pull Request, send either as a link to a repository fork or a +patch to the pgadmin-hackers@postgresql.org mailing list, clearly stating +that it’s a WIP, and noting what does or does not yet work.

  • +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/code_snippets.html b/pgsql/pgAdmin 4/docs/en_US/html/code_snippets.html new file mode 100644 index 0000000000000000000000000000000000000000..071af8ee098f65148f257f6c71bbef60dc3aa16a --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/code_snippets.html @@ -0,0 +1,733 @@ + + + + + + + + + + Code Snippets — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Code Snippets

+

This document contains code for some of the important classes, listed as +below:

+ +
+

PgAdminModule

+

PgAdminModule is inherited from Flask.Blueprint module. +This module defines a set of methods, properties and attributes, +that every module should implement.

+
class PgAdminModule(Blueprint):
+    """
+    Base class for every PgAdmin Module.
+
+    This class defines a set of method and attributes that
+    every module should implement.
+    """
+
+    def __init__(self, name, import_name, **kwargs):
+        kwargs.setdefault('url_prefix', '/' + name)
+        kwargs.setdefault('template_folder', 'templates')
+        kwargs.setdefault('static_folder', 'static')
+        self.submodules = []
+        self.parentmodules = []
+
+        super().__init__(name, import_name, **kwargs)
+
+    def register_preferences(self):
+        # To be implemented by child classes
+        pass
+
+    def register(self, app, options):
+        """
+        Override the default register function to automagically register
+        sub-modules at once.
+        """
+
+        super().register(app, options)
+
+        def create_module_preference():
+            # Create preference for each module by default
+            if hasattr(self, 'LABEL'):
+                self.preference = Preferences(self.name, self.LABEL)
+            else:
+                self.preference = Preferences(self.name, None)
+
+            self.register_preferences()
+
+        # Create and register the module preference object and preferences for
+        # it just before starting app
+        app.register_before_app_start(create_module_preference)
+
+        for module in self.submodules:
+            module.parentmodules.append(self)
+            if app.blueprints.get(module.name) is None:
+                app.register_blueprint(module)
+                app.register_logout_hook(module)
+
+    def get_own_messages(self):
+        """
+        Returns:
+            dict: the i18n messages used by this module, not including any
+                messages needed by the submodules.
+        """
+        return dict()
+
+    def get_own_menuitems(self):
+        """
+        Returns:
+            dict: the menuitems for this module, not including
+                any needed from the submodules.
+        """
+        return defaultdict(list)
+
+    def get_exposed_url_endpoints(self):
+        """
+        Returns:
+            list: a list of url endpoints exposed to the client.
+        """
+        return []
+
+    @property
+    def messages(self):
+        res = self.get_own_messages()
+
+        for module in self.submodules:
+            res.update(module.messages)
+        return res
+
+    @property
+    def menu_items(self):
+        menu_items = self.get_own_menuitems()
+        for module in self.submodules:
+            for key, value in module.menu_items.items():
+                menu_items[key].extend(value)
+        menu_items = dict((key, sorted(value, key=attrgetter('priority')))
+                          for key, value in menu_items.items())
+        return menu_items
+
+    @property
+    def exposed_endpoints(self):
+        res = self.get_exposed_url_endpoints()
+
+        for module in self.submodules:
+            res += module.exposed_endpoints
+
+        return res
+
+
+
+
+

NodeView

+

The NodeView class exposes basic REST APIs for different operations used by +the pgAdmin Browser. The basic idea has been taken from Flask’s MethodView class. Because +we need a lot more operations (not, just CRUD), we can not use it directly.

+
class NodeView(View, metaclass=type(MethodView)):
+    """
+    A PostgreSQL Object has so many operaions/functions apart from CRUD
+    (Create, Read, Update, Delete):
+    i.e.
+    - Reversed Engineered SQL
+    - Modified Query for parameter while editing object attributes
+      i.e. ALTER TABLE ...
+    - Statistics of the objects
+    - List of dependents
+    - List of dependencies
+    - Listing of the children object types for the certain node
+      It will used by the browser tree to get the children nodes
+
+    This class can be inherited to achieve the diffrent routes for each of the
+    object types/collections.
+
+       OPERATION   |             URL             | HTTP Method |    Method
+    ---------------+-----------------------------+-------------+--------------
+    List           | /obj/[Parent URL]/          | GET         | list
+    Properties     | /obj/[Parent URL]/id        | GET         | properties
+    Create         | /obj/[Parent URL]/          | POST        | create
+    Delete         | /obj/[Parent URL]/id        | DELETE      | delete
+    Update         | /obj/[Parent URL]/id        | PUT         | update
+
+    SQL (Reversed  | /sql/[Parent URL]/id        | GET         | sql
+    Engineering)   |
+    SQL (Modified  | /msql/[Parent URL]/id       | GET         | modified_sql
+    Properties)    |
+
+    Statistics     | /stats/[Parent URL]/id      | GET         | statistics
+    Dependencies   | /dependency/[Parent URL]/id | GET         | dependencies
+    Dependents     | /dependent/[Parent URL]/id  | GET         | dependents
+
+    Nodes          | /nodes/[Parent URL]/        | GET         | nodes
+    Current Node   | /nodes/[Parent URL]/id      | GET         | node
+
+    Children       | /children/[Parent URL]/id   | GET         | children
+
+    NOTE:
+    Parent URL can be seen as the path to identify the particular node.
+
+    i.e.
+    In order to identify the TABLE object, we need server -> database -> schema
+    information.
+    """
+    operations = dict({
+        'obj': [
+            {'get': 'properties', 'delete': 'delete', 'put': 'update'},
+            {'get': 'list', 'post': 'create'}
+        ],
+        'nodes': [{'get': 'node'}, {'get': 'nodes'}],
+        'sql': [{'get': 'sql'}],
+        'msql': [{'get': 'modified_sql'}],
+        'stats': [{'get': 'statistics'}],
+        'dependency': [{'get': 'dependencies'}],
+        'dependent': [{'get': 'dependents'}],
+        'children': [{'get': 'children'}]
+    })
+
+    @classmethod
+    def generate_ops(cls):
+        cmds = []
+        for op in cls.operations:
+            idx = 0
+            for ops in cls.operations[op]:
+                meths = []
+                for meth in ops:
+                    meths.append(meth.upper())
+                if len(meths) > 0:
+                    cmds.append({
+                        'cmd': op, 'req': (idx == 0),
+                        'with_id': (idx != 2), 'methods': meths
+                    })
+                idx += 1
+        return cmds
+
+    # Inherited class needs to modify these parameters
+    node_type = None
+    # Inherited class needs to modify these parameters
+    node_label = None
+    # This must be an array object with attributes (type and id)
+    parent_ids = []
+    # This must be an array object with attributes (type and id)
+    ids = []
+
+    @classmethod
+    def get_node_urls(cls):
+        assert cls.node_type is not None, \
+            "Please set the node_type for this class ({0})".format(
+                str(cls.__class__.__name__))
+        common_url = '/'
+        for p in cls.parent_ids:
+            common_url += '<{0}:{1}>/'.format(str(p['type']), str(p['id']))
+
+        id_url = None
+        for p in cls.ids:
+            id_url = '{0}<{1}:{2}>'.format(
+                common_url if not id_url else id_url,
+                p['type'], p['id'])
+
+        return id_url, common_url
+
+    def __init__(self, **kwargs):
+        self.cmd = kwargs['cmd']
+
+    # Check the existance of all the required arguments from parent_ids
+    # and return combination of has parent arguments, and has id arguments
+    def check_args(self, **kwargs):
+        has_id = has_args = True
+        for p in self.parent_ids:
+            if p['id'] not in kwargs:
+                has_args = False
+                break
+
+        for p in self.ids:
+            if p['id'] not in kwargs:
+                has_id = False
+                break
+
+        return has_args, has_id and has_args
+
+    def dispatch_request(self, *args, **kwargs):
+        http_method = flask.request.method.lower()
+        if http_method == 'head':
+            http_method = 'get'
+
+        assert self.cmd in self.operations, \
+            'Unimplemented command ({0}) for {1}'.format(
+                self.cmd,
+                str(self.__class__.__name__)
+            )
+
+        has_args, has_id = self.check_args(**kwargs)
+
+        assert (
+            self.cmd in self.operations and
+            (has_id and len(self.operations[self.cmd]) > 0 and
+             http_method in self.operations[self.cmd][0]) or
+            (not has_id and len(self.operations[self.cmd]) > 1 and
+             http_method in self.operations[self.cmd][1]) or
+            (len(self.operations[self.cmd]) > 2 and
+             http_method in self.operations[self.cmd][2])
+        ), \
+            'Unimplemented method ({0}) for command ({1}), which {2} ' \
+            'an id'.format(http_method,
+                           self.cmd,
+                           'requires' if has_id else 'does not require')
+        meth = None
+        if has_id:
+            meth = self.operations[self.cmd][0][http_method]
+        elif has_args and http_method in self.operations[self.cmd][1]:
+            meth = self.operations[self.cmd][1][http_method]
+        else:
+            meth = self.operations[self.cmd][2][http_method]
+
+        method = getattr(self, meth, None)
+
+        if method is None:
+            return make_json_response(
+                status=406,
+                success=0,
+                errormsg=gettext(
+                    'Unimplemented method ({0}) for this url ({1})').format(
+                        meth, flask.request.path
+                )
+            )
+
+        return method(*args, **kwargs)
+
+    @classmethod
+    def register_node_view(cls, blueprint):
+        cls.blueprint = blueprint
+        id_url, url = cls.get_node_urls()
+
+        commands = cls.generate_ops()
+
+        for c in commands:
+            cmd = c['cmd'].replace('.', '-')
+            if c['with_id']:
+                blueprint.add_url_rule(
+                    '/{0}{1}'.format(
+                        c['cmd'], id_url if c['req'] else url
+                    ),
+                    view_func=cls.as_view(
+                        '{0}{1}'.format(
+                            cmd, '_id' if c['req'] else ''
+                        ),
+                        cmd=c['cmd']
+                    ),
+                    methods=c['methods']
+                )
+            else:
+                blueprint.add_url_rule(
+                    '/{0}'.format(c['cmd']),
+                    view_func=cls.as_view(
+                        cmd, cmd=c['cmd']
+                    ),
+                    methods=c['methods']
+                )
+
+    def children(self, *args, **kwargs):
+        """Build a list of treeview nodes from the child nodes."""
+        children = self.get_children_nodes(*args, **kwargs)
+
+        # Return sorted nodes based on label
+        return make_json_response(
+            data=sorted(
+                children, key=lambda c: c['label']
+            )
+        )
+
+    def get_children_nodes(self, *args, **kwargs):
+        """
+        Returns the list of children nodes for the current nodes. Override this
+        function for special cases only.
+
+        :param args:
+        :param kwargs: Parameters to generate the correct set of tree node.
+        :return: List of the children nodes
+        """
+        children = []
+
+        for module in self.blueprint.submodules:
+            children.extend(module.get_nodes(*args, **kwargs))
+
+        return children
+
+
+
+
+

BaseDriver

+
class BaseDriver(metaclass=DriverRegistry):
+    """
+    class BaseDriver():
+
+    This is a base class for different server types.
+    Inherit this class to implement different type of database driver
+    implementation.
+
+    (For PostgreSQL/EDB Postgres Advanced Server, we will be using psycopg)
+
+    Abstract Properties:
+    -------- ----------
+    * Version (string):
+        Current version string for the database server
+
+    * libpq_version (string):
+        Current version string for the used libpq library
+
+    Abstract Methods:
+    -------- -------
+    * get_connection(*args, **kwargs)
+    - It should return a Connection class object, which may/may not be
+      connected to the database server.
+
+    * release_connection(*args, **kwargs)
+    - Implement the connection release logic
+
+    * gc()
+    - Implement this function to release the connections assigned in the
+      session, which has not been pinged from more than the idle timeout
+      configuration.
+    """
+
+    @property
+    @abstractmethod
+    def version(cls):
+        pass
+
+    @property
+    @abstractmethod
+    def libpq_version(cls):
+        pass
+
+    @abstractmethod
+    def get_connection(self, *args, **kwargs):
+        pass
+
+    @abstractmethod
+    def release_connection(self, *args, **kwargs):
+        pass
+
+    @abstractmethod
+    def gc_timeout(self):
+        pass
+
+
+
+
+

BaseConnection

+
class BaseConnection(metaclass=ABCMeta):
+    """
+    class BaseConnection()
+
+        It is a base class for database connection. A different connection
+        drive must implement this to expose abstract methods for this server.
+
+        General idea is to create a wrapper around the actual driver
+        implementation. It will be instantiated by the driver factory
+        basically. And, they should not be instantiated directly.
+
+
+    Abstract Methods:
+    -------- -------
+    * connect(**kwargs)
+      - Define this method to connect the server using that particular driver
+        implementation.
+
+    * execute_scalar(query, params, formatted_exception_msg)
+      - Implement this method to execute the given query and returns single
+        datum result.
+
+    * execute_async(query, params, formatted_exception_msg)
+      - Implement this method to execute the given query asynchronously and
+      returns result.
+
+    * execute_void(query, params, formatted_exception_msg)
+      - Implement this method to execute the given query with no result.
+
+    * execute_2darray(query, params, formatted_exception_msg)
+      - Implement this method to execute the given query and returns the result
+        as a 2 dimensional array.
+
+    * execute_dict(query, params, formatted_exception_msg)
+      - Implement this method to execute the given query and returns the result
+        as an array of dict (column name -> value) format.
+
+    * def async_fetchmany_2darray(records=-1, formatted_exception_msg=False):
+      - Implement this method to retrieve result of asynchronous connection and
+        polling with no_result flag set to True.
+        This returns the result as a 2 dimensional array.
+        If records is -1 then fetchmany will behave as fetchall.
+
+    * connected()
+      - Implement this method to get the status of the connection. It should
+        return True for connected, otherwise False
+
+    * reset()
+      - Implement this method to reconnect the database server (if possible)
+
+    * transaction_status()
+      - Implement this method to get the transaction status for this
+        connection. Range of return values different for each driver type.
+
+    * ping()
+      - Implement this method to ping the server. There are times, a connection
+        has been lost, but - the connection driver does not know about it. This
+        can be helpful to figure out the actual reason for query failure.
+
+    * _release()
+      - Implement this method to release the connection object. This should not
+        be directly called using the connection object itself.
+
+      NOTE: Please use BaseDriver.release_connection(...) for releasing the
+            connection object for better memory management, and connection pool
+            management.
+
+    * _wait(conn)
+      - Implement this method to wait for asynchronous connection to finish the
+        execution, hence - it must be a blocking call.
+
+    * _wait_timeout(conn, time)
+      - Implement this method to wait for asynchronous connection with timeout.
+        This must be a non blocking call.
+
+    * poll(formatted_exception_msg, no_result)
+      - Implement this method to poll the data of query running on asynchronous
+        connection.
+
+    * cancel_transaction(conn_id, did=None)
+      - Implement this method to cancel the running transaction.
+
+    * messages()
+      - Implement this method to return the list of the messages/notices from
+        the database server.
+
+    * rows_affected()
+      - Implement this method to get the rows affected by the last command
+        executed on the server.
+    """
+
+    ASYNC_OK = 1
+    ASYNC_READ_TIMEOUT = 2
+    ASYNC_WRITE_TIMEOUT = 3
+    ASYNC_NOT_CONNECTED = 4
+    ASYNC_EXECUTION_ABORTED = 5
+    ASYNC_TIMEOUT = 0.2
+    ASYNC_WAIT_TIMEOUT = 2
+    ASYNC_NOTICE_MAXLENGTH = 100000
+
+    @abstractmethod
+    def connect(self, **kwargs):
+        pass
+
+    @abstractmethod
+    def execute_scalar(self, query, params=None,
+                       formatted_exception_msg=False):
+        pass
+
+    @abstractmethod
+    def execute_async(self, query, params=None,
+                      formatted_exception_msg=True):
+        pass
+
+    @abstractmethod
+    def execute_void(self, query, params=None,
+                     formatted_exception_msg=False):
+        pass
+
+    @abstractmethod
+    def execute_2darray(self, query, params=None,
+                        formatted_exception_msg=False):
+        pass
+
+    @abstractmethod
+    def execute_dict(self, query, params=None,
+                     formatted_exception_msg=False):
+        pass
+
+    @abstractmethod
+    def async_fetchmany_2darray(self, records=-1,
+                                formatted_exception_msg=False):
+        pass
+
+    @abstractmethod
+    def connected(self):
+        pass
+
+    @abstractmethod
+    def reset(self):
+        pass
+
+    @abstractmethod
+    def transaction_status(self):
+        pass
+
+    @abstractmethod
+    def ping(self):
+        pass
+
+    @abstractmethod
+    def _release(self):
+        pass
+
+    @abstractmethod
+    def _wait(self, conn):
+        pass
+
+    @abstractmethod
+    def _wait_timeout(self, conn, time):
+        pass
+
+    @abstractmethod
+    def poll(self, formatted_exception_msg=True, no_result=False):
+        pass
+
+    @abstractmethod
+    def status_message(self):
+        pass
+
+    @abstractmethod
+    def rows_affected(self):
+        pass
+
+    @abstractmethod
+    def cancel_transaction(self, conn_id, did=None):
+        pass
+
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/coding_standards.html b/pgsql/pgAdmin 4/docs/en_US/html/coding_standards.html new file mode 100644 index 0000000000000000000000000000000000000000..e786f2708dded690361c40f4825dcffcd20e7c74 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/coding_standards.html @@ -0,0 +1,272 @@ + + + + + + + + + + Coding Standards — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Coding Standards

+

pgAdmin uses multiple technologies and multiple languages, each of which have +their own coding standards.

+
+

General

+

In all languages, indentations should be made with 4 spaces, and excessively long +lines wrapped where appropriate to ensure they can be read on smaller displays +(80 characters is used in many places, but this is not a required maximum size +as it’s quite wasteful on modern displays). Typically lines should not be longer +than 120 characters.

+

Comments should be included in all code where required to explain its +purpose or how it works if not obvious from a quick review of the code itself.

+
+
+

CSS 3

+

CSS3 is used for styling and layout throughout the application.

+

Most custom styling comes from individual modules which may advertise static +stylesheets to be included in the module that is loading them via hooks.

+

Styling overrides (for example, to alter the look and feel) will +typically be found in the overrides.css file in the main static file +directory for the application.

+

Styling should never be applied inline in HTML, always through an external +stylesheet, which should contain comments as appropriate to explain the usage +or purpose for the style.

+

Styles should be specified clearly, one per line. For example:

+
/* iFrames should have no border */
+iframe {
+    border-width: 0;
+}
+
+/* Ensure the codemirror editor displays full height gutters when resized */
+.CodeMirror, .CodeMirror-gutters {
+    height: 100% !important;
+}
+
+
+

All stylesheets must be CSS3 compliant.

+
+
+

HTML 5

+

HTML 5 is used for page structure throughout the application, in most cases +being rendered from templates by the Jinja2 template engine in Flask.

+

All HTML must be HTML 5 compliant.

+
+
+

Javascript

+

Client-side code is written in Javascript using ReactJS and various plugins. +Whilst much of the code is rendered from static files, there is also code that +is rendered from templates using Jinja2 (often to inject the users settings) or +constructed on the fly from module hooks.

+

A typical Javascript function might be formatted like this (this snipped is from +a template):

+
// Delete a server group
+function delete_server_group(item) {
+    alertify.confirm(
+        'Delete server group?',
+        'Are you sure you wish to delete the server group "{0}"?'.replace('{0}', tree.getLabel(item)),
+        function() {
+            var id = tree.getId(item)
+            $.post("{{ url_for('NODE-server-group.delete') }}", { id: id })
+                .done(function(data) {
+                    if (data.success == 0) {
+                        report_error(data.errormsg, data.info);
+                    } else {
+                        var next = tree.next(item);
+                        var prev = tree.prev(item);
+                        tree.remove(item);
+                        if (next.length) {
+                            tree.select(next);
+                        } else if (prev.length) {
+                            tree.select(prev);
+                        }
+                    }
+                }
+            )
+        },
+        null
+    )
+}
+
+
+

Note the use of a descriptive function name, using the underscore character to +separate words in all lower case, and short but descriptive lower case variable +names.

+
+

Note

+

From version 3.0 onwards, new or refactored code should be written using +ES6 features and conventions.

+
+
+
+

Python

+

Python is used for the backend web server. All code must be compatible with +Python 2.7 and should include PyDoc comments whilst following the official +Python coding standards defined in +PEP 8. An example function along +with the required file header is shown below:

+
##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+##########################################################################
+
+"""Integration hooks for server groups."""
+
+from flask import render_template, url_for
+from flask.ext.security import current_user
+
+from pgadmin.settings.settings_model import db, ServerGroup
+
+def get_nodes():
+    """Return a JSON document listing the server groups for the user"""
+    groups = ServerGroup.query.filter_by(user_id=current_user.id)
+
+    value = ''
+    for group in groups:
+        value += '{"id":%d,"label":"%s","icon":"icon-server-group","inode":true},' \
+                 % (group.id, group.name)
+
+    value = value[:-1]
+
+    return value
+
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/collation_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/collation_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..c13c72d6f8a31b94a58f107e3dbb5920ca4a4ee1 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/collation_dialog.html @@ -0,0 +1,236 @@ + + + + + + + + + + Collation Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Collation Dialog

+

Use the Collation dialog to define a collation. A collation is an SQL schema +object that maps a SQL name to operating system locales. To create a collation, +you must have a CREATE privilege on the destination schema.

+

The Collation dialog organizes the development of a collation through the +following dialog tabs: General and Definition. The SQL tab displays the +SQL code generated by dialog selections.

+Collation dialog general tab +

Use the fields in the General tab to identify the collation:

+
    +
  • Use the Name field to provide a name for the collation. The collation name +must be unique within a schema. The name will be displayed in the pgAdmin +tree control.

  • +
  • Select the name of the owner from the drop-down listbox in the Owner field.

  • +
  • Select the name of the schema in which the collation will reside from the +drop-down listbox in the Schema field.

  • +
  • Store notes about the collation in the Comment field.

  • +
+

Click the Definition tab to continue.

+Collation dialog definition tab +

Use the fields in the Definition tab to specify the operating system locale +settings:

+
    +
  • Use the drop-down listbox next to Copy collation to select the name of an +existing collation to copy. The new collation will have the same properties +as the existing one, but will be an independent object. If you choose to copy +an existing collation, you cannot modify the collation properties displayed on +this tab.

  • +
  • Use the Locale field to specify a locale; a locale specifies language and +language formatting characteristics. If you specify this, you cannot specify +either of the following parameters. To view a list of locales supported by +your Linux system use the command locale -a.

  • +
  • Use the LC_COLLATE field to specify a locale with specified string sort +order. The locale must be applicable to the current database encoding. (See +CREATE DATABASE for details.)

  • +
  • Use the LC_CTYPE field to specify a locale with specified character +classification. The locale must be applicable to the current database encoding. +(See CREATE DATABASE for details.)

  • +
  • Use the drop-down listbox next to Locale Provider to select a locale services associated +with the collation. Possible values are: icu, libc. libc is the default.

  • +
  • Move the switch next to Deterministic to YES to specify whether the collation should use +deterministic comparisons. By default, this option is set to true. In a +deterministic comparison, strings that are not byte-wise equal are considered +unequal, even if they are considered logically equal in the comparison.

  • +
  • Use the Rules field to specify a rules for customizing the behavior of the collation. +It includes considerations such as character ordering, case sensitivity, and accent +sensitivity.

  • +
  • Use the Version field to specify version string to store with the collation object.

  • +
+

Click the SQL tab to continue.

+

Your entries in the Collation dialog generate a SQL command (see an example b +elow). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Collation dialog:

+Collation dialog sql tab +

The example shown demonstrates creating a collation named french that uses the +rules specified for the locale, fr-BI-x-icu. The collation is owned by +*postgres.

+
    +
  • Click the Info button (i) to access online help. For more information about +setting a locale, see Chapter 22.1 Locale Support of the PostgreSQL core +documentation:

    +
    +
    +
  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/column_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/column_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..557aba6c32751b0df89a976ec49161985484bdd5 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/column_dialog.html @@ -0,0 +1,286 @@ + + + + + + + + + + Column Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Column Dialog

+

Use the Column dialog to add a column to an existing table or modify a column +definition.

+

The Column dialog organizes the development of a column through the following +dialog tabs: General, Definition, and Security. The SQL tab displays the +SQL code generated by dialog selections.

+Column dialog general tab +

Use the fields in the General tab to identify the column:

+
    +
  • Use the Name field to add a descriptive name for the column. The name will +be displayed in the pgAdmin tree control. This field is required.

  • +
  • Store notes about the column in the Comment field.

  • +
+

Click the Definition tab to continue.

+Column dialog definition tab +

Use the fields in the Definition tab to add parameters for the column. (Fields +are disabled if inapplicable.)

+
    +
  • Use the drop-down listbox next to Data Type to select a data type for the +column. For more information on the data types that are supported by +PostgreSQL, refer to Chapter 8 of the Postgres core documentation. This field +is required.

  • +
  • Use the Length/Precision and Scale fields to specify the maximum number of +significant digits in a numeric value, or the maximum number of characters in +a text value.

  • +
  • Use the drop-down listbox next to Collation to apply a collation setting to +the column.

  • +
  • Use the drop-down listbox next to Compression to set the compression method +for the column. Compression is supported only for variable-width data types, +and is used only when the column’s storage mode is main or extended. This +option is available from v14 and above.

  • +
  • Use the drop-down listbox next to Storage to set the storage mode for the +column. This option is available from v16 and above.

  • +
+

Click the Constraints tab to continue.

+Column dialog constraints tab +

Use the fields in the Constraints tab to specify constraints for the column. +(Fields are disabled if inapplicable.)

+
    +
  • Use the Default Value field to specify a default data value.

  • +
  • Move the Not Null switch to the Yes position to specify the column may not +contain null values. The default is No.

  • +
  • Use the Type field to specify the column type (NONE/IDENTITY/GENERATED). +The default is NONE.

  • +
+

Click the IDENTITY type to create Identity column.

+Column dialog constraints tab +

Use the following fields to create IDENTITY column. Identity columns are +applicable for PG/EPAS version 10 and above.

+
    +
  • Use the Identity field to specify ALWAYS or BY DEFAULT. This clause is +used to determine how the sequence value is given precedence over a +user-specified value in an INSERT statement.

  • +
  • Use the Increment field to specify which value is added to the current +sequence value to create a new value.

  • +
  • Provide a value in the Start field to specify the beginning value of the +sequence. The default starting value is MINVALUE for ascending sequences and +MAXVALUE for descending ones.

  • +
  • Provide a value in the Minimum field to specify the minimum value a sequence +can generate. If this clause is not supplied or NO MINVALUE is specified, +then defaults will be used. The defaults are 1 and -263-1 for ascending and +descending sequences, respectively.

  • +
  • Provide a value in the Maximum field to specify the maximum value for the +sequence. If this clause is not supplied or NO MAXVALUE is specified, then +default values will be used. The defaults are 263-1 and -1 for ascending and +descending sequences, respectively.

  • +
  • Provide a value in the Cache field to specify how many sequence numbers are +to be preallocated and stored in memory for faster access. The minimum value +is 1 (only one value can be generated at a time, i.e., no cache), and this is +also the default.

  • +
  • Move the Cycled switch to the Yes position to allow the sequence to wrap +around when the MAXVALUE or the MINVALUE has been reached by an ascending or +descending sequence respectively. If the limit is reached, the next number +generated will be the MINVALUE or MAXVALUE, respectively. The default is No.

  • +
+

Click the GENERATED type to create Generated column.

+Column dialog constraints tab +

Use the following fields to create GENERATED column. Generated columns are +applicable for PG/EPAS version 12 and above.

+
    +
  • Use the Expression field to specify the generation expression. It can +refer to other columns in the table, but not other generated columns. +Any functions and operators used must be immutable. References to other +tables are not allowed.

  • +
+

Click the Variables tab to continue.

+Column dialog variables tab +

Use the Variables tab to specify the number of distinct values that may be +present in the column; this value overrides estimates made by the ANALYZE +command. Click the Add icon (+) to add a Name/Value pair:

+
    +
  • Select the name of the variable from the drop-down listbox in the Name field.

    +
    +
      +
    • Select n_distinct to specify the number of distinct values for the column.

    • +
    • Select n_distinct_inherited to specify the number of distinct values +for the table and its children.

    • +
    +
    +
  • +
  • Specify the number of distinct values in the Value field. For more +information, see the documentation for +ALTER TABLE.

  • +
+

Click the Add icon (+) to specify each additional Name/Value pair; to +discard a variable, click the trash icon to the left of the row and confirm +deletion in the Delete Row popup.

+

Click the Security tab to continue.

+Column dialog security tab +

Use the Security tab to assign attributes and define security labels. Click +the Add icon (+) to add each security label selection:

+
    +
  • Specify a security label provider in the Provider field. The named provider +must be loaded and must consent to the proposed labeling operation.

  • +
  • Specify a a security label in the Security Label field. The meaning of a +given label is at the discretion of the label provider. PostgreSQL places no +restrictions on whether or how a label provider must interpret security +labels; it merely provides a mechanism for storing them.

  • +
+

Click the Add icon (+) to assign additional security labels; to discard a +security label, click the trash icon to the left of the row and confirm deletion +in the Delete Row popup.

+

Click the SQL tab to continue.

+

Your entries in the Column dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Column dialog:

+Column dialog sql tab +

The example shown demonstrates creating a column named sal in the table +named jobhist.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/compound_trigger_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/compound_trigger_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..3409d20a38076763dcdd1334c7fe7d0884c363c7 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/compound_trigger_dialog.html @@ -0,0 +1,203 @@ + + + + + + + + + + Compound Trigger Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Compound Trigger Dialog

+

Use the Compound Trigger dialog to create a compound trigger or modify an +existing compound trigger. Compound Trigger is supported only for EPAS server +12 and above. A compound trigger executes a specified code when certain events +occur.

+

The Compound Trigger dialog organizes the development of a compound trigger +through the following dialog tabs: General, Events, and Code. The SQL +tab displays the SQL code generated by dialog selections.

+Compound Trigger dialog general tab +

Use the fields in the General tab to identify the compound trigger:

+
    +
  • Use the Name field to add a descriptive name for the compound trigger. This +must be distinct from the name of any other compound trigger for the same table. +The name will be displayed in the pgAdmin tree control.

  • +
  • Store notes about the compound trigger in the Comment field.

  • +
+Trigger enabled in dialog tab +
    +
  • Trigger enabled field is available in compound trigger dialog once the trigger is created. +You can select one of the four options available.

  • +
+

Click the Events tab to continue.

+Compound Trigger dialog events tab +

Use the fields in the Events tab to specify how and when the compound trigger fires:

+
    +
  • Select the type of event(s) that will invoke the compound trigger; to select +an event type, move the switch next to the event to the YES position. +The supported event types are INSERT, UPDATE, DELETE and TRUNCATE. +Views cannot have TRUNCATE triggers.

  • +
  • Use the When field to provide a boolean condition that will invoke the +compound trigger.

  • +
  • If defining a column-specific compound trigger, use the Columns field to +specify the columns or columns that are the target of the compound trigger.

  • +
+

Click the Code tab to continue.

+Compound Trigger dialog code tab +

Use the Code field to specify the code for the five timing events +BEFORE STATEMENT, AFTER STATEMENT, BEFORE EACH ROW, AFTER EACH ROW, +INSTEAD OF EACH ROW that will be invoked when the compound trigger fires. +Basic template is provided with place holders.

+

Click the SQL tab to continue.

+

Your entries in the Compound Trigger dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Compound Trigger dialog:

+Compound Trigger dialog sql tab +

The example demonstrates creating a compound trigger named test_ct.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/config_py.html b/pgsql/pgAdmin 4/docs/en_US/html/config_py.html new file mode 100644 index 0000000000000000000000000000000000000000..2b3f63bbd55d587c25205d82e5283ba79a1d28a6 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/config_py.html @@ -0,0 +1,1140 @@ + + + + + + + + + + The config.py File — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

The config.py File

+

There are multiple configuration files that are read at startup by pgAdmin. These +files are used for configuration options that:

+
    +
  • may be required to be set prior to startup of pgAdmin as they control how +the application will operate.

  • +
  • system administrators may wish to control across an organisation to enforce +security policies.

  • +
  • are so rarely or unlikely to be changed that it doesn’t +make sense to allow them to be changed through the user interface.

  • +
+

The configuration files are as follows:

+
    +
  • config.py: This is the main configuration file, and should not be modified. +It can be used as a reference for configuration settings, that may be overridden +in one of the following files.

  • +
  • config_distro.py: This file is read after config.py and is intended for +packagers to change any settings that are required for their pgAdmin distribution. +This may typically include certain paths and file locations. This file is optional, +and may be created by packagers in the same directory as config.py if +needed.

  • +
  • config_local.py: This file is read after config_distro.py and is intended +for the owner of the installation to change any default or packaging specific settings +that they may wish to adjust to meet local preferences or standards.This file is optional, +and may be created by users in the same directory as config.py if +needed.

  • +
  • config_system.py: This file is read after config_local.py and is +intended for system administrators to include settings that are configured +system-wide from a secure location that users cannot normally modify and that +is outside of the pgAdmin installation. The location for this file varies +based on the platform, and only needs to be created if desired.

    + + + + + + + + + + + + + + + + + +

    Platform

    File Location

    Linux

    /etc/pgadmin/config_system.py

    macOS

    /Library/Preferences/pgadmin/config_system.py

    Windows

    %CommonProgramFiles%\pgadmin\config_system.py

    +
  • +
+
+

Note

+

If the SERVER_MODE or DATA_DIR settings are changed in +config_distro.py, config_local.py, or config_system.py +LOG_FILE, SQLITE_PATH, SESSION_DB_PATH, STORAGE_DIR, KERBEROS_CCACHE_DIR, +and AZURE_CREDENTIAL_CACHE_DIR values will be set based on DATA_DIR unless +values are explicitly overridden for any of the variable in any of the +above file.

+
+

The default config.py file is shown below for reference:

+
# -*- coding: utf-8 -*-
+
+##########################################################################
+#
+# pgAdmin 4 - PostgreSQL Tools
+#
+# Copyright (C) 2013 - 2024, The pgAdmin Development Team
+# This software is released under the PostgreSQL Licence
+#
+# config.py - Core application configuration settings
+#
+##########################################################################
+
+import builtins
+import logging
+import os
+import sys
+from collections import OrderedDict
+
+# We need to include the root directory in sys.path to ensure that we can
+# find everything we need when running in the standalone runtime.
+root = os.path.dirname(os.path.realpath(__file__))
+if sys.path[0] != root:
+    sys.path.insert(0, root)
+
+# The config database connection pool size.
+# Setting this to 0 will remove any limit.
+CONFIG_DATABASE_CONNECTION_POOL_SIZE = 5
+# The number of connections allowed to overflow beyond
+# the connection pool size.
+CONFIG_DATABASE_CONNECTION_MAX_OVERFLOW = 100
+
+from pgadmin.utils import env, IS_WIN, fs_short_path
+from version import APP_VERSION, APP_RELEASE, APP_REVISION, APP_SUFFIX, \
+    APP_VERSION_INT
+from branding import APP_NAME, APP_ICON, APP_COPYRIGHT, APP_PATH, \
+    APP_WIN_PATH, APP_SHORT_NAME, APP_DEFAULT_EMAIL
+
+##########################################################################
+# Misc stuff
+##########################################################################
+
+# Path to the online help.
+HELP_PATH = '../../../docs/en_US/_build/html/'
+
+# Languages we support in the UI
+LANGUAGES = {
+    'en': 'English',
+    'zh': 'Chinese (Simplified)',
+    'cs': 'Czech',
+    'fr': 'French',
+    'de': 'German',
+    'id': 'Indonesian',
+    'it': 'Italian',
+    'ja': 'Japanese',
+    'ko': 'Korean',
+    'pl': 'Polish',
+    'pt_BR': 'Portuguese (Brazilian)',
+    'ru': 'Russian',
+    'es': 'Spanish',
+}
+
+# DO NOT CHANGE UNLESS YOU KNOW WHAT YOU ARE DOING!
+# List of modules to skip when dynamically loading
+MODULE_BLACKLIST = ['test']
+
+# DO NOT CHANGE UNLESS YOU KNOW WHAT YOU ARE DOING!
+# List of treeview browser nodes to skip when dynamically loading
+NODE_BLACKLIST = []
+
+##########################################################################
+# Server settings
+##########################################################################
+
+# The server mode determines whether or not we're running on a web server
+# requiring user authentication, or desktop mode which uses an automatic
+# default login.
+#
+# DO NOT DISABLE SERVER MODE IF RUNNING ON A WEBSERVER!!
+#
+# We only set SERVER_MODE if it's not already set. That's to allow the
+# runtime to force it to False.
+#
+# NOTE: If you change the value of SERVER_MODE or DATA_DIR in an included
+#       config file, you may also need to redefine any values below that are
+#       derived from it, notably various paths such as LOG_FILE, SQLITE_PATH,
+#       SESSION_DB_PATH, STORAGE_DIR, KERBEROS_CCACHE_DIR, and
+#       AZURE_CREDENTIAL_CACHE_DIR
+
+if (not hasattr(builtins, 'SERVER_MODE')) or builtins.SERVER_MODE is None:
+    SERVER_MODE = True
+else:
+    SERVER_MODE = builtins.SERVER_MODE
+
+# HTTP headers to search for CSRF token when it is not provided in the form.
+# Default is ['X-CSRFToken', 'X-CSRF-Token']
+WTF_CSRF_HEADERS = ['X-pgA-CSRFToken']
+
+# User ID (email address) to use for the default user in desktop mode.
+# The default should be fine here, as it's not exposed in the app.
+DESKTOP_USER = APP_DEFAULT_EMAIL
+
+# This option allows the user to host the application on a LAN
+# Default hosting is on localhost (DEFAULT_SERVER='localhost').
+# To host pgAdmin4 over LAN set DEFAULT_SERVER='0.0.0.0' (or a specific
+# adaptor address.
+#
+# NOTE: This is NOT recommended for production use, only for debugging
+# or testing. Production installations should be run as a WSGI application
+# behind Apache HTTPD.
+DEFAULT_SERVER = '127.0.0.1'
+
+# The default port on which the app server will listen if not set in the
+# environment by the runtime
+DEFAULT_SERVER_PORT = 5050
+
+# This param is used to override the default web server information about
+# the web technology and the frameworks being used in the application
+# An attacker could use this information to fingerprint underlying operating
+# system and research known exploits for the specific version of
+# software in use
+WEB_SERVER = 'Python'
+
+# Enable X-Frame-Option protection.
+# Set to one of "SAMEORIGIN", "ALLOW-FROM origin" or "" to disable.
+# Note that "DENY" is NOT supported (and will be silently ignored).
+# See https://tools.ietf.org/html/rfc7034 for more info.
+X_FRAME_OPTIONS = "SAMEORIGIN"
+
+# The Content-Security-Policy header allows you to restrict how resources
+# such as JavaScript, CSS, or pretty much anything that the browser loads.
+# see https://content-security-policy.com/#source_list for more info
+# e.g. "default-src https: data: 'unsafe-inline' 'unsafe-eval';"
+CONTENT_SECURITY_POLICY = "default-src ws: http: data: blob: 'unsafe-inline'" \
+                          " 'unsafe-eval';"
+
+# STRICT_TRANSPORT_SECURITY_ENABLED when set to True will set the
+# Strict-Transport-Security header
+STRICT_TRANSPORT_SECURITY_ENABLED = False
+
+# The Strict-Transport-Security header tells the browser to convert all HTTP
+# requests to HTTPS, preventing man-in-the-middle (MITM) attacks.
+# e.g. 'max-age=31536000; includeSubDomains'
+STRICT_TRANSPORT_SECURITY = "max-age=31536000; includeSubDomains"
+
+# The X-Content-Type-Options header forces the browser to honor the response
+# content type instead of trying to detect it, which can be abused to
+# generate a cross-site scripting (XSS) attack.
+# e.g. nosniff
+X_CONTENT_TYPE_OPTIONS = "nosniff"
+
+# The browser will try to prevent reflected XSS attacks by not loading the
+# page if the request contains something that looks like JavaScript and the
+# response contains the same data. e.g. '1; mode=block'
+X_XSS_PROTECTION = "1; mode=block"
+
+# This param is used to validate ALLOWED_HOSTS for the application
+# This will be used to avoid Host Header Injection attack
+# ALLOWED_HOSTS = ['225.0.0.0/8', '226.0.0.0/7', '228.0.0.0/6']
+# ALLOWED_HOSTS = ['127.0.0.1', '192.168.0.1']
+# if ALLOWED_HOSTS= [] then it will accept all ips (and application will be
+# vulnerable to Host Header Injection attack)
+ALLOWED_HOSTS = []
+
+# Hashing algorithm used for password storage
+SECURITY_PASSWORD_HASH = 'pbkdf2_sha512'
+
+# Minimum password length
+PASSWORD_LENGTH_MIN = 6
+
+# Reverse Proxy parameters
+# You must tell the middleware how many proxies set each header
+# so it knows what values to trust.
+# See https://tinyurl.com/yyg7r9av
+# for more information.
+
+# Number of values to trust for X-Forwarded-For
+PROXY_X_FOR_COUNT = 1
+
+# Number of values to trust for X-Forwarded-Proto.
+PROXY_X_PROTO_COUNT = 1
+
+# Number of values to trust for X-Forwarded-Host.
+PROXY_X_HOST_COUNT = 0
+
+# Number of values to trust for X-Forwarded-Port.
+PROXY_X_PORT_COUNT = 1
+
+# Number of values to trust for X-Forwarded-Prefix.
+PROXY_X_PREFIX_COUNT = 0
+
+# NOTE: CSRF_SESSION_KEY, SECRET_KEY and SECURITY_PASSWORD_SALT are no
+#       longer part of the main configuration, but are stored in the
+#       configuration databases 'keys' table and are auto-generated.
+
+# COMPRESSION
+COMPRESS_MIMETYPES = [
+    'text/html', 'text/css', 'text/xml', 'text/javascript',
+    'application/json', 'application/javascript'
+]
+COMPRESS_LEVEL = 9
+COMPRESS_MIN_SIZE = 500
+
+# Set the cache control max age for static files in flask to 1 year
+SEND_FILE_MAX_AGE_DEFAULT = 31556952
+
+# This will be added to static urls as url parameter with value as
+# APP_VERSION_INT for cache busting on version upgrade. If the value is set as
+# None or empty string then it will not be added.
+# eg - http:localhost:5050/pgadmin.css?intver=3.13
+APP_VERSION_PARAM = 'ver'
+
+# Add the internal version param to below extensions only
+APP_VERSION_EXTN = ('.css', '.js', '.html', '.svg', '.png', '.gif', '.ico')
+
+# Data directory for storage of config settings etc. This shouldn't normally
+# need to be changed - it's here as various other settings depend on it.
+# On Windows, we always store data in %APPDATA%\$(APP_WIN_PATH). On other
+# platforms, if we're in server mode we use /var/lib/$(APP_PATH),
+# otherwise ~/.$(APP_PATH)
+if IS_WIN:
+    # Use the short path on windows
+    DATA_DIR = os.path.realpath(
+        os.path.join(fs_short_path(env('APPDATA')), APP_WIN_PATH)
+    )
+else:
+    if SERVER_MODE:
+        DATA_DIR = os.path.join('/var/lib/', APP_PATH)
+    else:
+        DATA_DIR = os.path.realpath(
+            os.path.expanduser('~/' + '.' + APP_PATH + '/')
+        )
+
+# An optional login banner to show security warnings/disclaimers etc. at
+# login and password recovery etc. HTML may be included for basic formatting,
+# For example:
+# LOGIN_BANNER = "<h4>Authorised Users Only!</h4>" \
+#                "Unauthorised use is strictly forbidden."
+LOGIN_BANNER = ""
+
+##########################################################################
+# Log settings
+##########################################################################
+
+# Debug mode?
+DEBUG = False
+
+# Application log level - one of:
+#   CRITICAL 50
+#   ERROR    40
+#   WARNING  30
+#   SQL      25
+#   INFO     20
+#   DEBUG    10
+#   NOTSET    0
+CONSOLE_LOG_LEVEL = logging.WARNING
+FILE_LOG_LEVEL = logging.WARNING
+
+# Log format.
+JSON_LOGGER = False
+CONSOLE_LOG_FORMAT_JSON = OrderedDict([
+    ("time", "asctime"),
+    ("message", "message"),
+    ("level", "levelname")
+])
+
+FILE_LOG_FORMAT_JSON = OrderedDict([
+    ("time", "asctime"),
+    ("message", "message"),
+    ("level", "levelname")
+])
+
+
+CONSOLE_LOG_FORMAT = '%(asctime)s: %(levelname)s\t%(name)s:\t%(message)s'
+FILE_LOG_FORMAT = '%(asctime)s: %(levelname)s\t%(name)s:\t%(message)s'
+
+# Log file name. This goes in the data directory, except on non-Windows
+# platforms in server mode.
+if SERVER_MODE and not IS_WIN:
+    LOG_FILE = os.path.join('/var/log', APP_PATH, APP_SHORT_NAME + '.log')
+else:
+    LOG_FILE = os.path.join(DATA_DIR, APP_SHORT_NAME + '.log')
+
+# Log rotation setting
+# Log file will be rotated considering values for LOG_ROTATION_SIZE
+# & LOG_ROTATION_AGE. Rotated file will be named in format
+# - LOG_FILE.Y-m-d_H-M-S
+LOG_ROTATION_SIZE = 10  # In MBs
+LOG_ROTATION_AGE = 1440  # In minutes
+LOG_ROTATION_MAX_LOG_FILES = 90  # Maximum number of backups to retain
+##########################################################################
+# Server Connection Driver Settings
+##########################################################################
+
+# The default driver used for making connection with PostgreSQL
+PG_DEFAULT_DRIVER = 'psycopg3'
+
+# Maximum allowed idle time in minutes before which releasing the connection
+# for the particular session. (in minutes)
+MAX_SESSION_IDLE_TIME = 60
+
+##########################################################################
+# External Database Settings
+#
+# All configuration settings are stored by default in the SQLite database.
+# In order to use external databases like PostgreSQL sets the value of
+# CONFIG_DATABASE_URI like below:
+# dialect+driver://username:password@host:port/database
+#
+# PostgreSQL:
+# postgresql://username:password@host:port/database
+# Specify Schema Name
+# postgresql://username:password@host:port/database?options=-csearch_path=pgadmin
+# Using PGPASS file
+# postgresql://username@host:port?options=-csearch_path=pgadmin
+##########################################################################
+CONFIG_DATABASE_URI = ''
+
+##########################################################################
+# User account and settings storage
+##########################################################################
+
+# The default path to the SQLite database used to store user accounts and
+# settings. This default places the file in the same directory as this
+# config file, but generates an absolute path for use througout the app.
+SQLITE_PATH = env('SQLITE_PATH') or \
+    os.path.join(DATA_DIR, APP_SHORT_NAME + '.db')
+
+# SQLITE_TIMEOUT will define how long to wait before throwing the error -
+# OperationError due to database lock. On slower system, you may need to change
+# this to some higher value.
+# (Default: 500 milliseconds)
+SQLITE_TIMEOUT = 500
+
+# Allow database connection passwords to be saved if the user chooses.
+# Set to False to disable password saving.
+ALLOW_SAVE_PASSWORD = True
+
+# Maximum number of history queries stored per user/server/database
+MAX_QUERY_HIST_STORED = 20
+
+##########################################################################
+# Server-side session storage path
+#
+# SESSION_DB_PATH (Default: $HOME/.pgadmin4/sessions)
+##########################################################################
+#
+# We use SQLite for server-side session storage. There will be one
+# SQLite database object per session created.
+#
+# Specify the path used to store your session objects.
+#
+# If the specified directory does not exist, the setup script will create
+# it with permission mode 700 to keep the session database secure.
+#
+# On certain systems, you can use shared memory (tmpfs) for maximum
+# scalability, for example, on Ubuntu:
+#
+# SESSION_DB_PATH = '/run/shm/pgAdmin4_session'
+#
+##########################################################################
+SESSION_DB_PATH = os.path.join(DATA_DIR, 'sessions')
+
+SESSION_COOKIE_NAME = 'pga4_session'
+
+##########################################################################
+# Mail server settings
+##########################################################################
+
+# These settings are used when running in web server mode for confirming
+# and resetting passwords etc.
+# See: http://pythonhosted.org/Flask-Mail/ for more info
+MAIL_SERVER = 'localhost'
+MAIL_PORT = 25
+MAIL_USE_SSL = False
+MAIL_USE_TLS = False
+MAIL_USERNAME = ''
+MAIL_PASSWORD = ''
+MAIL_DEBUG = False
+
+# Flask-Security overrides Flask-Mail's MAIL_DEFAULT_SENDER setting, so
+# that should be set as such:
+SECURITY_EMAIL_SENDER = 'no-reply@localhost'
+
+##########################################################################
+# Mail content settings
+##########################################################################
+
+# These settings define the content of password reset emails
+SECURITY_EMAIL_SUBJECT_PASSWORD_RESET = "Password reset instructions for %s" \
+                                        % APP_NAME
+SECURITY_EMAIL_SUBJECT_PASSWORD_NOTICE = "Your %s password has been reset" \
+                                         % APP_NAME
+SECURITY_EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE = \
+    "Your password for %s has been changed" % APP_NAME
+
+##########################################################################
+# Email address validation
+##########################################################################
+CHECK_EMAIL_DELIVERABILITY = False
+SECURITY_EMAIL_VALIDATOR_ARGS = \
+    {"check_deliverability": CHECK_EMAIL_DELIVERABILITY}
+
+##########################################################################
+# Upgrade checks
+##########################################################################
+
+# Check for new versions of the application?
+UPGRADE_CHECK_ENABLED = True
+
+# Where should we get the data from?
+UPGRADE_CHECK_URL = 'https://www.pgadmin.org/versions.json'
+
+# What key should we look at in the upgrade data file?
+UPGRADE_CHECK_KEY = 'pgadmin4'
+
+# Which CA file should we use?
+# Default to cacert.pem in the same directory as config.py et al.
+CA_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)),
+                       "cacert.pem")
+
+# Check if the detected browser is supported
+CHECK_SUPPORTED_BROWSER = True
+
+##########################################################################
+# Storage Manager storage url config settings
+# If user sets STORAGE_DIR to empty it will show all volumes if platform
+# is Windows, '/' if it is Linux, Mac or any other unix type system.
+
+# For example:
+# 1. STORAGE_DIR = get_drive("C") or get_drive() # return C:/ by default
+# where C can be any drive character such as "D", "E", "G" etc
+# 2. Set path manually like
+# STORAGE_DIR = "/path/to/directory/"
+##########################################################################
+STORAGE_DIR = os.path.join(DATA_DIR, 'storage')
+
+##########################################################################
+# Default locations for binary utilities (pg_dump, pg_restore etc)
+#
+# These are intentionally left empty in the main config file, but are
+# expected to be overridden by packagers in config_distro.py.
+#
+# A default location can be specified for each database driver ID, in
+# a dictionary. Either an absolute or relative path can be specified.
+#
+# Version-specific defaults can also be specified, which will take priority
+# over un-versioned paths.
+#
+# In cases where it may be difficult to know what the working directory
+# is, "$DIR" can be specified. This will be replaced with the path to the
+# top-level pgAdmin4.py file. For example, on macOS we might use:
+#
+# $DIR/../../SharedSupport
+#
+##########################################################################
+DEFAULT_BINARY_PATHS = {
+    "pg": "",
+    "pg-12": "",
+    "pg-13": "",
+    "pg-14": "",
+    "pg-15": "",
+    "pg-16": "",
+    "ppas": "",
+    "ppas-12": "",
+    "ppas-13": "",
+    "ppas-14": "",
+    "ppas-15": "",
+    "ppas-16": ""
+}
+
+##########################################################################
+
+# Admin can specify fixed binary paths to prevent users from changing.
+# It will take precedence over DEFAULT_BINARY_PATHS.
+
+FIXED_BINARY_PATHS = {
+    "pg": "",
+    "pg-12": "",
+    "pg-13": "",
+    "pg-14": "",
+    "pg-15": "",
+    "pg-16": "",
+    "ppas": "",
+    "ppas-12": "",
+    "ppas-13": "",
+    "ppas-14": "",
+    "ppas-15": "",
+    "ppas-16": ""
+}
+
+##########################################################################
+# Test settings - used primarily by the regression suite, not for users
+##########################################################################
+
+# The default path for SQLite database for testing
+TEST_SQLITE_PATH = os.path.join(DATA_DIR, 'test_pgadmin4.db')
+
+##########################################################################
+# Allows flask application to response to the each request asynchronously
+##########################################################################
+THREADED_MODE = True
+
+##########################################################################
+# Do not allow SQLALCHEMY to track modification as it is going to be
+# deprecated in future
+##########################################################################
+SQLALCHEMY_TRACK_MODIFICATIONS = False
+
+##########################################################################
+# Number of records to fetch in one batch in query tool when query result
+# set is large.
+##########################################################################
+ON_DEMAND_RECORD_COUNT = 1000
+
+##########################################################################
+# Allow users to display Gravatar image for their username in Server mode
+##########################################################################
+SHOW_GRAVATAR_IMAGE = True
+
+##########################################################################
+# Set cookie path and options
+##########################################################################
+COOKIE_DEFAULT_PATH = '/'
+COOKIE_DEFAULT_DOMAIN = None
+SESSION_COOKIE_DOMAIN = None
+SESSION_COOKIE_SAMESITE = 'Lax'
+SESSION_COOKIE_SECURE = False
+SESSION_COOKIE_HTTPONLY = True
+
+#########################################################################
+# Skip storing session in files and cache for specific paths
+#########################################################################
+SESSION_SKIP_PATHS = [
+    '/misc/ping'
+]
+
+##########################################################################
+# Session expiration support
+##########################################################################
+# SESSION_EXPIRATION_TIME is the interval in Days. Session will be
+# expire after the specified number of *days*.
+SESSION_EXPIRATION_TIME = 1
+
+# Make SESSION_EXPIRATION_TIME to 1 week in DESKTOP mode
+if not SERVER_MODE:
+    SESSION_EXPIRATION_TIME = 7
+
+# CHECK_SESSION_FILES_INTERVAL is interval in Hours. Application will check
+# the session files for cleanup after specified number of *hours*.
+CHECK_SESSION_FILES_INTERVAL = 24
+
+# USER_INACTIVITY_TIMEOUT is interval in Seconds. If the pgAdmin screen is left
+# unattended for <USER_INACTIVITY_TIMEOUT> seconds then the user will
+# be logged out. When set to 0, the timeout will be disabled.
+# If pgAdmin doesn't detect any activity in the time specified (in seconds),
+# the user will be forcibly logged out from pgAdmin. Set to zero to disable
+# the timeout.
+# Note: This is applicable only for SERVER_MODE=True.
+USER_INACTIVITY_TIMEOUT = 0
+
+# OVERRIDE_USER_INACTIVITY_TIMEOUT when set to True will override
+# USER_INACTIVITY_TIMEOUT when long running queries in the Query Tool
+# or Debugger are running. When the queries complete, the inactivity timer
+# will restart in this case. If set to False, user inactivity may cause
+# transactions or in-process debugging sessions to be aborted.
+OVERRIDE_USER_INACTIVITY_TIMEOUT = True
+
+##########################################################################
+# SSH Tunneling supports only for Python 2.7 and 3.4+
+##########################################################################
+SUPPORT_SSH_TUNNEL = True
+# Allow SSH Tunnel passwords to be saved if the user chooses.
+# Set to False to disable password saving.
+ALLOW_SAVE_TUNNEL_PASSWORD = False
+
+##########################################################################
+# Master password is used to encrypt/decrypt saved server passwords
+# Applicable for desktop mode only
+##########################################################################
+MASTER_PASSWORD_REQUIRED = True
+
+##########################################################################
+
+# pgAdmin encrypts the database connection and ssh tunnel password using a
+# master password or pgAdmin login password (for other authentication sources)
+# before storing it in the pgAdmin configuration database.
+#
+# Below setting is used to allow the user to specify the path to a script
+# or program that will return an encryption key which will be used to
+# encrypt the passwords. This setting is used only in server mode when
+# auth sources are oauth, Kerberos, and webserver.
+#
+# You can pass the current username as an argument to the external script
+# by specifying %u in config value.
+# E.g. - MASTER_PASSWORD_HOOK = '<PATH>/passwdgen_script.sh %u'
+##########################################################################
+MASTER_PASSWORD_HOOK = None
+
+##########################################################################
+
+# Allows pgAdmin4 to create session cookies based on IP address, so even
+# if a cookie is stolen, the attacker will not be able to connect to the
+# server using that stolen cookie.
+# Note: This can cause problems when the server is deployed in dynamic IP
+# address hosting environments, such as Kubernetes or behind load
+# balancers. In such cases, this option should be set to False.
+##########################################################################
+ENHANCED_COOKIE_PROTECTION = True
+
+##########################################################################
+# External Authentication Sources
+##########################################################################
+
+# Default setting is internal
+# External Supported Sources: ldap, kerberos, oauth2
+# Multiple authentication can be achieved by setting this parameter to
+# ['ldap', 'internal'] or ['oauth2', 'internal'] or
+# ['webserver', 'internal'] etc.
+# pgAdmin will authenticate the user with ldap/oauth2 whatever first in the
+# list, in case of failure the second authentication option will be considered.
+
+AUTHENTICATION_SOURCES = ['internal']
+
+##########################################################################
+# MAX_LOGIN_ATTEMPTS which sets the number of failed login attempts that
+# are allowed. If this value is exceeded the account is locked and can be
+# reset by an administrator. By setting the variable to the value zero
+# this feature is deactivated.
+##########################################################################
+MAX_LOGIN_ATTEMPTS = 3
+
+##########################################################################
+# Only consider password to check the failed login attempts, email is
+# excluded from this check
+LOGIN_ATTEMPT_FIELDS = ['password']
+##########################################################################
+# LDAP Configuration
+##########################################################################
+
+# After ldap authentication, user will be added into the SQLite database
+# automatically, if set to True.
+# Set it to False, if user should not be added automatically,
+# in this case Admin has to add the user manually in the SQLite database.
+LDAP_AUTO_CREATE_USER = True
+
+# Connection timeout
+LDAP_CONNECTION_TIMEOUT = 10
+
+# Server connection details (REQUIRED)
+# example: ldap://<ip-address>:<port> or ldap://<hostname>:<port>
+LDAP_SERVER_URI = 'ldap://<ip-address>:<port>'
+
+# The LDAP attribute containing user names. In OpenLDAP, this may be 'uid'
+# whilst in AD, 'sAMAccountName' might be appropriate. (REQUIRED)
+LDAP_USERNAME_ATTRIBUTE = '<User-id>'
+
+##########################################################################
+# 3 ways to configure LDAP as follows (Choose anyone):
+
+# 1. Dedicated User binding
+
+# LDAP Bind User DN Example: cn=username,dc=example,dc=com
+# Set this parameter to allow the connection to bind using a dedicated user.
+# After the connection is made, the pgadmin login user will be further
+# authenticated by the username and password provided
+# at the login screen.
+LDAP_BIND_USER = None
+
+# LDAP Bind User Password
+LDAP_BIND_PASSWORD = None
+
+# OR ####################
+# 2. Anonymous Binding
+
+# Set this parameter to allow the anonymous bind.
+# After the connection is made, the pgadmin login user will be further
+# authenticated by the username and password provided
+
+LDAP_ANONYMOUS_BIND = False
+
+# OR ####################
+# 3. Bind as pgAdmin user
+
+# BaseDN (REQUIRED)
+# AD example:
+# (&(objectClass=user)(memberof=CN=MYGROUP,CN=Users,dc=example,dc=com))
+# OpenLDAP example: CN=Users,dc=example,dc=com
+LDAP_BASE_DN = '<Base-DN>'
+
+# Configure the bind format string
+# Default: LDAP_BIND_FORMAT="
+#   {LDAP_USERNAME_ATTRIBUTE}={LDAP_USERNAME},{LDAP_BASE_DN}"
+# The current available options are:
+# LDAP_USERNAME_ATTRIBUTE, LDAP_USERNAME, LDAP_BASE_DN
+# Example: LDAP_BIND_FORMAT="myldapuser@sales.example.com"
+#          LDAP_BIND_FORMAT="NET\\myldapuser"
+LDAP_BIND_FORMAT = '{LDAP_USERNAME_ATTRIBUTE}={LDAP_USERNAME},{LDAP_BASE_DN}'
+
+##########################################################################
+
+# Search ldap for further authentication (REQUIRED)
+# It can be optional while bind as pgAdmin user
+LDAP_SEARCH_BASE_DN = '<Search-Base-DN>'
+
+# The LDAP attribute indicates whether the DN (Distinguished Names)
+# are case sensitive or not
+LDAP_DN_CASE_SENSITIVE = False
+
+# Filter string for the user search.
+# For OpenLDAP, '(cn=*)' may well be enough.
+# For AD, you might use '(objectClass=user)' (REQUIRED)
+LDAP_SEARCH_FILTER = '(objectclass=*)'
+
+# Search scope for users (one of BASE, LEVEL or SUBTREE)
+LDAP_SEARCH_SCOPE = 'SUBTREE'
+
+# Use TLS? If the URI scheme is ldaps://, this is ignored.
+LDAP_USE_STARTTLS = False
+
+# TLS/SSL certificates. Specify if required, otherwise leave empty
+LDAP_CA_CERT_FILE = ''
+LDAP_CERT_FILE = ''
+LDAP_KEY_FILE = ''
+
+##########################################################################
+
+# Some flaky LDAP servers returns malformed schema. If True, no exception
+# will be raised and schema is thrown away but authentication will be done.
+# This parameter should remain False, as recommended.
+LDAP_IGNORE_MALFORMED_SCHEMA = False
+
+##########################################################################
+# Kerberos Configuration
+##########################################################################
+
+KRB_APP_HOST_NAME = DEFAULT_SERVER
+
+# If the default_keytab_name is not set in krb5.conf or
+# the KRB_KTNAME environment variable is not set then, explicitly set
+# the Keytab file
+
+KRB_KTNAME = '<KRB5_KEYTAB_FILE>'
+
+# After kerberos authentication, user will be added into the SQLite database
+# automatically, if set to True.
+# Set it to False, if user should not be added automatically,
+# in this case Admin has to add the user manually in the SQLite database.
+
+KRB_AUTO_CREATE_USER = True
+
+KERBEROS_CCACHE_DIR = os.path.join(DATA_DIR, 'krbccache')
+
+#############################################################################
+# Create local directory to store azure credential cache
+#############################################################################
+
+AZURE_CREDENTIAL_CACHE_DIR = os.path.join(DATA_DIR, 'azurecredentialcache')
+
+##########################################################################
+# OAuth2 Configuration
+##########################################################################
+
+# Multiple OAUTH2 providers can be added in the list like [{...},{...}]
+# All parameters are required
+
+OAUTH2_CONFIG = [
+    {
+        # The name of the of the oauth provider, ex: github, google
+        'OAUTH2_NAME': None,
+        # The display name, ex: Google
+        'OAUTH2_DISPLAY_NAME': '<Oauth2 Display Name>',
+        # Oauth client id
+        'OAUTH2_CLIENT_ID': None,
+        # Oauth secret
+        'OAUTH2_CLIENT_SECRET': None,
+        # URL to generate a token,
+        # Ex: https://github.com/login/oauth/access_token
+        'OAUTH2_TOKEN_URL': None,
+        # URL is used for authentication,
+        # Ex: https://github.com/login/oauth/authorize
+        'OAUTH2_AUTHORIZATION_URL': None,
+        # server metadata url might optional for your provider
+        'OAUTH2_SERVER_METADATA_URL': None,
+        # Oauth base url, ex: https://api.github.com/
+        'OAUTH2_API_BASE_URL': None,
+        # Name of the Endpoint, ex: user
+        'OAUTH2_USERINFO_ENDPOINT': None,
+        # Oauth scope, ex: 'openid email profile'
+        # Note that an 'email' claim is required in the resulting profile
+        'OAUTH2_SCOPE': None,
+        # The claim which is used for the username. If the value is empty the
+        # email is used as username, but if a value is provided,
+        # the claim has to exist.
+        'OAUTH2_USERNAME_CLAIM': None,
+        # Font-awesome icon, ex: fa-github
+        'OAUTH2_ICON': None,
+        # UI button colour, ex: #0000ff
+        'OAUTH2_BUTTON_COLOR': None,
+        # The additional claims to check on user ID Token or Userinfo response.
+        # This is useful to provide additional authorization checks
+        # before allowing access.
+        # Example for GitLab: allowing all maintainers teams, and a specific
+        # developers group to access pgadmin:
+        # 'OAUTH2_ADDITIONAL_CLAIMS': {
+        #     'https://gitlab.org/claims/groups/maintainer': [
+        #           'kuberheads/applications',
+        #           'kuberheads/dba',
+        #           'kuberheads/support'
+        #      ],
+        #     'https://gitlab.org/claims/groups/developer': [
+        #           'kuberheads/applications/team01'
+        #      ],
+        # }
+        # Example for AzureAD:
+        # 'OAUTH2_ADDITIONAL_CLAIMS': {
+        #     'groups': ["0760b6cf-170e-4a14-91b3-4b78e0739963"],
+        #     'wids': ["cf1c38e5-3621-4004-a7cb-879624dced7c"],
+        # }
+        'OAUTH2_ADDITIONAL_CLAIMS': None,
+        # Set this variable to False to disable SSL certificate verification
+        # for OAuth2 provider.
+        # This may need to set False, in case of self-signed certificates.
+        # Ref: https://github.com/psf/requests/issues/6071
+        'OAUTH2_SSL_CERT_VERIFICATION': True,
+        # set this variable to invalidate the session of the oauth2 provider
+        # Example for keycloak:
+        # 'OAUTH2_LOGOUT_URL':
+        # 'https://example.com/realms/master/protocol/openid-connect/logout?post_logout_redirect_uri={redirect_uri}&id_token_hint={id_token}'
+        'OAUTH2_LOGOUT_URL': None
+    }
+]
+
+# After Oauth authentication, user will be added into the SQLite database
+# automatically, if set to True.
+# Set it to False, if user should not be added automatically,
+# in this case Admin has to add the user manually in the SQLite database.
+
+OAUTH2_AUTO_CREATE_USER = True
+
+##########################################################################
+# Webserver Configuration
+##########################################################################
+
+WEBSERVER_AUTO_CREATE_USER = True
+
+# REMOTE_USER variable will be used to check the environment variable
+# is set or not first, if not available,
+# request header will be checked for the same.
+# Possible values: REMOTE_USER, HTTP_X_FORWARDED_USER, X-Forwarded-User
+
+WEBSERVER_REMOTE_USER = 'REMOTE_USER'
+
+##########################################################################
+# Two-factor Authentication Configuration
+##########################################################################
+
+# Set it to True, to enable the two-factor authentication
+MFA_ENABLED = True
+
+# Set it to True, to ask the users to register forcefully for the
+# two-authentication methods on logged-in.
+MFA_FORCE_REGISTRATION = False
+
+# pgAdmin supports Two-factor authentication by either sending an one-time code
+# to an email, or using the TOTP based application like Google Authenticator.
+MFA_SUPPORTED_METHODS = ["email", "authenticator"]
+
+# NOTE: Please set the 'Mail server settings' to use 'email' as two-factor
+#       authentication method.
+
+# Subject for the email verification code
+# Default: <APP_NAME> - Verification Code
+# e.g.  pgAdmin 4 - Verification Code
+MFA_EMAIL_SUBJECT = None
+
+##########################################################################
+# PSQL tool settings
+##########################################################################
+# This will enable PSQL tool in pgAdmin when running in server mode.
+# PSQL is always enabled in Desktop mode, however in server mode it is
+# disabled by default because users can run arbitrary commands on the
+# server through it.
+ENABLE_PSQL = False
+
+##########################################################################
+# ENABLE_BINARY_PATH_BROWSING setting is used to enable the browse button
+# while selecting binary path for the database server in server mode.
+# In Desktop mode it is always enabled and setting is of no use.
+##########################################################################
+ENABLE_BINARY_PATH_BROWSING = False
+
+##########################################################################
+# In server mode, the SHARED_STORAGE setting is used to enable shared storage.
+# Specify the name, path, and restricted_access values that should be shared
+# between users. When restricted_access is set to True, non-admin users cannot
+# upload/add, delete, or rename files/folders in shared storage, only admins
+# can do that. Users must provide the absolute path to the folder, and the name
+# can be anything they see on the user interface.
+# [{ 'name': 'Shared 1', 'path': '/shared_folder',
+#   'restricted_access': True/False}]
+##########################################################################
+SHARED_STORAGE = []
+
+#############################################################################
+# AUTO_DISCOVER_SERVERS setting is used to enable the pgAdmin to discover the
+# database server automatically on the local machine.
+# When it is set to False, pgAdmin will not discover servers installed on
+# the local machine.
+#############################################################################
+AUTO_DISCOVER_SERVERS = True
+
+#############################################################################
+# SERVER_HEARTBEAT_TIMEOUT is used to send the server heartbeat to server
+# from the client. This will resolve the orphan database issue once
+# browser tab is closed.
+#############################################################################
+SERVER_HEARTBEAT_TIMEOUT = 30  # In seconds
+
+#############################################################################
+# ENABLE_SERVER_PASS_EXEC_CMD is used to enable/disable Password exec command
+# field in server properties. This is used to specify a shell command to be
+# executed to retrieve a password to be used for server authentication.
+# This setting is applicable only for server mode.
+#############################################################################
+ENABLE_SERVER_PASS_EXEC_CMD = False
+
+#############################################################################
+# Patch the default config with custom config and other manipulations
+#############################################################################
+from pgadmin.evaluate_config import evaluate_and_patch_config
+locals().update(evaluate_and_patch_config(locals()))
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/connect_error.html b/pgsql/pgAdmin 4/docs/en_US/html/connect_error.html new file mode 100644 index 0000000000000000000000000000000000000000..96ae533c1930f33d29ab553801ac3f277cf3c69c --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/connect_error.html @@ -0,0 +1,182 @@ + + + + + + + + + + Connection Error — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Connection Error

+

When connecting to a PostgreSQL server, you may get an error message. If you +encounter an error message, please review the message carefully; each error +message attempts to incorporate the information you’ll need to resolve the +problem. For more details about specific errors, please locate the error +message in the list below:

+

Connection to the server has been lost

+Connection to the server has been lost +

This error message indicates that the connection attempt has taken longer than +the specified threshold; there may be a problem with the connection properties +provided on the Server dialog, network connectivity issues, or the server may +not be running.

+

could not connect to Server: Connection refused

+Could not connect to server +
+
If pgAdmin displays this message, there are two possible reasons for this:
    +
  • the database server isn’t running - simply start it.

  • +
  • the server isn’t configured to accept TCP/IP requests on the address shown.

  • +
+
+
+

For security reasons, a PostgreSQL server “out of the box” doesn’t listen on +TCP/IP ports. Instead, it must be enabled to listen for TCP/IP requests. This +can be done by adding listen_addresses=’*’; this will make the server accept +connections on any IP interface.

+

For further information, please refer to the PostgreSQL documentation about +runtime configuration.

+

FATAL: no pg_hba.conf entry

+No pg_hba.conf entry +

If pgAdmin displays this message when connecting, your server can be contacted +correctly over the network, but is not configured to accept your connection. +Your client has not been detected as a legal user for the database.

+

To connect to a server, the pg_hba.conf file on the database server must be +configured to accept connections from the host of the pgAdmin client. Modify +the pg_hba.conf file on the database server host, and add an entry in the form:

+
+
    +
  • host template1 postgres 192.168.0.0/24 md5 for an IPV4 network

  • +
  • host template1 postgres ::ffff:192.168.0.0/120 md5 for an IPV6 network

  • +
+
+

For more information, please refer to the PostgreSQL documentation about +client authentication.

+

FATAL: password authentication failed

+Password authentication failed +

The password authentication failed for user error message indicates there +may be a problem with the password you entered. Retry the password to confirm +you entered it correctly. If the error message returns, make sure that you have +the correct password, that you are authorized to access the server, and that +the access has been correctly configured in the server’s postgresql.conf +configuration file.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/connect_to_server.html b/pgsql/pgAdmin 4/docs/en_US/html/connect_to_server.html new file mode 100644 index 0000000000000000000000000000000000000000..52f1844e6f0b780eea1880cce959a9e297d27272 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/connect_to_server.html @@ -0,0 +1,170 @@ + + + + + + + + + + Connect to Server — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Connect to Server

+

Use the Connect to Server dialog to authenticate with a defined server and +access the objects stored on the server through the pgAdmin tree control. To +access the dialog, right click on the server name in the pgAdmin tree control, +and select Connect Server… from the context menu.

+Connect to server dialog +

Provide authentication information for the selected server:

+
+
    +
  • Use the Password field to provide the password of the user that is +associated with the defined server.

  • +
  • Check the box next to Save Password to instruct the server to save the +password for future connections; if you save the password, you will not be +prompted when reconnecting to the database server with this server +definition.

  • +
+
+

When using SSH Tunneling, the Connect to Server dialog will prompt for the SSH +Tunnel and Database server passwords if not already saved.

+Connect to server dialog +

Provide authentication information for the selected server:

+
+
    +
  • Use the Password field to provide the password of the user that is +associated with the defined server.

  • +
  • Check the box next to respective Save Password to instruct the server to +save the password for future connections; if you save the password, you will +not be prompted when reconnecting to the database server with this server +definition.

  • +
+
+

The pgAdmin client displays a message in a green status bar in the lower right +corner when the server connects successfully.

+

If you receive an error message while attempting a connection, verify that your +network is allowing the pgAdmin host and the host of the database server to +communicate. For detailed information about a specific error message, please see +the Connection Error help page.

+

To review or modify connection details, right-click on the name of the server, +and select Properties… from the context menu.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/connecting.html b/pgsql/pgAdmin 4/docs/en_US/html/connecting.html new file mode 100644 index 0000000000000000000000000000000000000000..00aeb14dabaa8ff5f32becc8b8ee0df5ac5cec16 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/connecting.html @@ -0,0 +1,199 @@ + + + + + + + + + + Connecting To A Server — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Connecting To A Server

+

Before you can use the pgAdmin client to manage the objects that reside on your +Postgres server, you must define a connection to the server. You can +(optionally) use the Server Group dialog to create server groups to organize +the server connections within the tree control for easier management. To open +the Server Group dialog, right-click on the Servers node of the tree +control, and select Server Group from the Create menu.

+ +

Use the fields on the Server dialog to define the connection properties for +each new server that you wish to manage with pgAdmin. To open the Server +dialog, right-click on the Servers node of the tree control, and select +Server from the Register menu.

+ +

Alternatively you can use the Cloud Deployment wizard to deploy a new +PostgreSQL instance in the cloud, and connect to it.

+ +

A master password is required to secure and later unlock saved server passwords. +It is set by the user and can be disabled using config.

+ +

After defining a server connection, right-click on the server name, and select +Connect to server to authenticate with the server, and start using pgAdmin to +manage objects that reside on the server.

+ +

Server definitions (and their groups) can be exported to a JSON file and +re-imported to the same or a different system to enable easy pre-configuration +of pgAdmin.

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/container_deployment.html b/pgsql/pgAdmin 4/docs/en_US/html/container_deployment.html new file mode 100644 index 0000000000000000000000000000000000000000..887280434c70ef8a270e6498dfad65bc9408de73 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/container_deployment.html @@ -0,0 +1,582 @@ + + + + + + + + + + Container Deployment — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Container Deployment

+

pgAdmin can be deployed in a container using the image at:

+
+
+

There are various tags that you can select from to get the version of pgAdmin +that you want, using a command such as this if you’re using Docker:

+
docker pull dpage/pgadmin4:<tag name>
+
+
+

where <tag name> is one of the following:

+ ++++ + + + + + + + + + + + + + + + + + + + +

Tag name

Description

latest

The most recent release.

8.4

A specific version (8.4 in this case).

8

the latest release of a specific major version (major version 8 in this case).

snapshot

The latest nightly test build.

+
+

PostgreSQL Utilities

+

The PostgreSQL utilities pg_dump, pg_dumpall, pg_restore and psql are +included in the container to allow backups to be created and restored and other +maintenance functions to be executed. Multiple versions are included in the +following directories to allow use with different versions of the database +server:

+
    +
  • PostgreSQL 12: /usr/local/pgsql-12

  • +
  • PostgreSQL 13: /usr/local/pgsql-13

  • +
  • PostgreSQL 14: /usr/local/pgsql-14

  • +
  • PostgreSQL 15: /usr/local/pgsql-15

  • +
  • PostgreSQL 16: /usr/local/pgsql-16

  • +
+

The default binary paths set in the container are as follows:

+
DEFAULT_BINARY_PATHS = {
+    'pg-16': '/usr/local/pgsql-16',
+    'pg-15': '/usr/local/pgsql-15',
+    'pg-14': '/usr/local/pgsql-14',
+    'pg-13': '/usr/local/pgsql-13',
+    'pg-12': '/usr/local/pgsql-12'
+}
+
+
+

this may be changed in the Preferences Dialog.

+
+
+

Environment Variables

+

The container will accept the following variables at startup:

+

PGADMIN_DEFAULT_EMAIL

+

This is the email address used when setting up the initial administrator account +to login to pgAdmin. This variable is required and must be set at launch time.

+

PGADMIN_DEFAULT_PASSWORD

+

This is the password used when setting up the initial administrator account to +login to pgAdmin. This variable is required and must be set at launch time.

+

PGADMIN_DEFAULT_PASSWORD_FILE

+

This is the password used when setting up the initial administrator account to +login to pgAdmin. This value should be set to docker secret in order to set +the password. This variable is supported in docker swarm environment or while creating +container with docker compose. PGADMIN_DEFAULT_PASSWORD or PGADMIN_DEFAULT_PASSWORD_FILE +variable is required and must be set at launch time.

+

PGADMIN_DISABLE_POSTFIX

+

Default: <null>

+

If left unset, a Postfix server will be started to deliver password reset +emails.

+

If set to any value, the Postfix server will not be started, and pgAdmin will +need to be configured to use an external mail server using the PGADMIN_CONFIG_ +options below.

+

This option is useful if you’re running in an environment that prevents the use +of sudo to start Postfix, or if you wish to use an external mail server.

+

PGADMIN_ENABLE_TLS

+

Default: <null>

+

If left un-set, the container will listen on port 80 for connections in plain +text. If set to any value, the container will listen on port 443 for TLS +connections.

+

When TLS is enabled, a certificate and key must be provided. Typically these +should be stored on the host file system and mounted from the container. The +expected paths are /certs/server.cert and /certs/server.key

+

PGADMIN_LISTEN_ADDRESS

+

Default: [::]

+

Specify the local address that the servers listens on. The default should work +for most users - in IPv4-only environments, this may need to be set to +0.0.0.0.

+

PGADMIN_LISTEN_PORT

+

Default: 80 or 443 (if TLS is enabled)

+

Allows the port that the server listens on to be set to a specific value rather +than using the default.

+

PGADMIN_SERVER_JSON_FILE

+

Default: /pgadmin4/servers.json

+

Override the default file path for the server definition list. See the +/pgadmin4/servers.json mapped file below for more information. See the format +of the Servers JSON file.

+

PGADMIN_PREFERENCES_JSON_FILE

+

Default: /pgadmin4/preferences.json

+

Override the default file path for the preferences customization at the container creation. See the +/pgadmin4/preferences.json mapped file below for more information. See the format +of the Preferences JSON file.

+

GUNICORN_ACCESS_LOGFILE

+

Default: - (stdout)

+

Specify an output file in which to store the Gunicorn access logs, instead of +sending them to stdout.

+

GUNICORN_LIMIT_REQUEST_LINE

+

Default: 8190

+

Set the maximum size of HTTP request line in bytes. By default the pgAdmin +container uses the maximum limited size offered by Gunicorn as some requests +can be quite large. In exceptional cases this value can be set to 0 (zero) to +specify “unlimited”, however this poses a potential denial of service hazard.

+

GUNICORN_THREADS

+

Default: 25

+

Adjust the number of threads the Gunicorn server uses to handle incoming +requests. This should typically be left as-is, except in highly loaded systems +where it may be increased.

+

PGADMIN_CONFIG_*

+

This is a variable prefix that can be used to override any of the configuration +options in pgAdmin’s config.py file. Add the PGADMIN_CONFIG_ prefix to any +variable name from config.py and give the value in the format ‘string value’ +for strings, True/False for booleans or 123 for numbers. See below for an +example.

+

Settings are written to /pgadmin4/config_distro.py within the container, which +is read after /pgadmin4/config.py and before /pgadmin4/config_local.py. +Any settings given will therefore override anything in config.py, but can be +overridden by settings in config_local.py.

+

Settings are only written to /pgadmin4/config_distro.py once, typically on +first launch of the container. If /pgadmin4/config_distro.py contains one or +more lines, then no changes are made; for example, if the container instance is +restarted, or /pgadmin4/config_distro.py is mapped to a file on persistent +storage (not recommended - use /pgadmin4/config_local.py instead)!

+

See The config.py File for more information on the available configuration settings.

+
+
+

Mapped Files and Directories

+

The following files or directories can be mapped from the container onto the +host machine to allow configuration to be customised and shared between +instances.

+
+

Warning

+

Warning: pgAdmin runs as the pgadmin user (UID: 5050) in the +pgadmin group (GID: 5050) in the container. You must ensure that all files +are readable, and where necessary (e.g. the working/session directory) +writeable for this user on the host machine. For example:

+
sudo chown -R 5050:5050 <host_directory>
+
+
+

On some filesystems that do not support extended attributes, it may not be +possible to run pgAdmin without specifying a value for PGADMIN_LISTEN_PORT +that is greater than 1024. In such cases, specify an alternate port when +launching the container by adding the environment variable, for example:

+
-e 'PGADMIN_LISTEN_PORT=5050'
+
+
+

Don’t forget to adjust any host-container port mapping accordingly.

+
+

/var/lib/pgadmin

+

This is the working directory in which pgAdmin stores session data, user files, +configuration files, and it’s configuration database. Mapping this directory +onto the host machine gives you an easy way to maintain configuration between +invocations of the container.

+

/pgadmin4/config_local.py

+

This file can be used to override configuration settings in pgAdmin. Settings +found in config.py can be overridden with deployment specific values if +required. Settings in config_local.py will also override anything specified in +the container environment through PGADMIN_CONFIG_ prefixed variables.

+

/pgadmin4/servers.json

+

If this file is mapped, server definitions found in it will be loaded at launch +time. This allows connection information to be pre-loaded into the instance of +pgAdmin in the container. Note that server definitions are only loaded on first +launch, i.e. when the configuration database is created, and not on subsequent +launches using the same configuration database.

+

/pgadmin4/preferences.json

+

If this file is mapped, preferences defined in it will be updated at launch +time. This allows customization of preferences settings into the instance of +pgAdmin in the container. Note that preferences are only set on first +launch, i.e. when the configuration database is created, and not on subsequent +launches using the same configuration database.

+

/certs/server.cert

+

If TLS is enabled, this file will be used as the servers TLS certificate.

+

/certs/server.key

+

If TLS is enabled, this file will be used as the key file for the servers TLS +certificate.

+
+
+

Examples

+

Run a simple container over port 80:

+
docker pull dpage/pgadmin4
+docker run -p 80:80 \
+    -e 'PGADMIN_DEFAULT_EMAIL=user@domain.com' \
+    -e 'PGADMIN_DEFAULT_PASSWORD=SuperSecret' \
+    -d dpage/pgadmin4
+
+
+

Run a simple container over port 80, setting some configuration options:

+
docker pull dpage/pgadmin4
+docker run -p 80:80 \
+    -e 'PGADMIN_DEFAULT_EMAIL=user@domain.com' \
+    -e 'PGADMIN_DEFAULT_PASSWORD=SuperSecret' \
+    -e 'PGADMIN_CONFIG_ENHANCED_COOKIE_PROTECTION=True' \
+    -e 'PGADMIN_CONFIG_LOGIN_BANNER="Authorised users only!"' \
+    -e 'PGADMIN_CONFIG_CONSOLE_LOG_LEVEL=10' \
+    -d dpage/pgadmin4
+
+
+

Run a TLS secured container using a shared config/storage directory in +/private/var/lib/pgadmin on the host, and servers pre-loaded from +/tmp/servers.json on the host:

+
docker pull dpage/pgadmin4
+docker run -p 443:443 \
+    -v /private/var/lib/pgadmin:/var/lib/pgadmin \
+    -v /path/to/certificate.cert:/certs/server.cert \
+    -v /path/to/certificate.key:/certs/server.key \
+    -v /tmp/servers.json:/pgadmin4/servers.json \
+    -e 'PGADMIN_DEFAULT_EMAIL=user@domain.com' \
+    -e 'PGADMIN_DEFAULT_PASSWORD=SuperSecret' \
+    -e 'PGADMIN_ENABLE_TLS=True' \
+    -d dpage/pgadmin4
+
+
+
+
+

Reverse Proxying

+

Sometimes it’s desirable to have users connect to pgAdmin through a reverse +proxy rather than directly to the container it’s running in. The following +examples show how this can be achieved. With traditional reverse proxy servers +such as Nginx, pgAdmin is running in a container on +the same host, with port 5050 on the host mapped to port 80 on the container, +for example:

+
docker pull dpage/pgadmin4
+docker run -p 5050:80 \
+    -e "PGADMIN_DEFAULT_EMAIL=user@domain.com" \
+    -e "PGADMIN_DEFAULT_PASSWORD=SuperSecret" \
+    -d dpage/pgadmin4
+
+
+
+

pgAdmin X-Forwarded-* Configuration

+

pgAdmin needs to understand how many proxies set each header so it knows what +values to trust. The configuration parameters for the X-Forwarded-* options +which are used for this purpose are shown below, along with their default +values.

+

pgAdmin is configured by default to be able to run behind a reverse proxy even +on a non-standard port and these config options don’t normally need to be +changed. If you’re running an unusual configuration (such as multiple reverse +proxies) you can adjust the configuration to suit.

+
# Number of values to trust for X-Forwarded-For
+PROXY_X_FOR_COUNT = 1
+
+# Number of values to trust for X-Forwarded-Proto.
+PROXY_X_PROTO_COUNT = 0
+
+# Number of values to trust for X-Forwarded-Host.
+PROXY_X_HOST_COUNT = 0
+
+# Number of values to trust for X-Forwarded-Port.
+PROXY_X_PORT_COUNT = 1
+
+# Number of values to trust for X-Forwarded-Prefix.
+PROXY_X_PREFIX_COUNT = 0
+
+
+
+
+

HTTP via Nginx

+

A configuration similar to the following can be used to create a simple HTTP +reverse proxy listening for all hostnames with Nginx:

+
server {
+    listen 80;
+    server_name _;
+
+    location / {
+        proxy_set_header Host $host;
+        proxy_pass http://localhost:5050/;
+        proxy_redirect off;
+    }
+}
+
+
+

If you wish to host pgAdmin under a subdirectory rather than on the root of the +server, you must specify the location and set the X-Script-Name header which +tells the pgAdmin container how to rewrite paths:

+
server {
+    listen 80;
+    server_name _;
+
+    location /pgadmin4/ {
+        proxy_set_header X-Script-Name /pgadmin4;
+        proxy_set_header Host $host;
+        proxy_pass http://localhost:5050/;
+        proxy_redirect off;
+    }
+}
+
+
+

If Nginx is also running in a container, there is no need to map the pgAdmin +port to the host, provided the two containers are running in the same Docker +network. In such a configuration, the proxy_pass option would be changed to +point to the pgAdmin container within the Docker network.

+
+
+

HTTPS via Nginx

+

The following configuration can be used to serve pgAdmin over HTTPS to the user +whilst the backend container is serving plain HTTP to the proxy server. In this +configuration we not only set X-Script-Name, but also X-Scheme to tell the +pgAdmin server to generate any URLs using the correct scheme. A redirect from +HTTP to HTTPS is also included. The certificate and key paths may need to be +adjusted as appropriate to the specific deployment:

+
server {
+    listen 80;
+    return 301 https://$host$request_uri;
+}
+
+server {
+    listen 443;
+    server_name _;
+
+    ssl_certificate /etc/nginx/server.cert;
+    ssl_certificate_key /etc/nginx/server.key;
+
+    ssl on;
+    ssl_session_cache builtin:1000 shared:SSL:10m;
+    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
+    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
+    ssl_prefer_server_ciphers on;
+
+    location /pgadmin4/ {
+        proxy_set_header X-Script-Name /pgadmin4;
+        proxy_set_header X-Scheme $scheme;
+        proxy_set_header Host $host;
+        proxy_pass http://localhost:5050/;
+        proxy_redirect off;
+    }
+}
+
+
+
+
+

Traefik

+

Configuring Traefik is straightforward for either HTTP +or HTTPS when running pgAdmin in a container as it will automatically configure +itself to serve content from containers that are running on the local machine, +virtual hosting them at <container_name>.<domain_name>, where the domain +name is that specified in the Traefik configuration. The container is typically +launched per the example below:

+
docker pull dpage/pgadmin4
+docker run --name "pgadmin4" \
+    -e "PGADMIN_DEFAULT_EMAIL=user@domain.com" \
+    -e "PGADMIN_DEFAULT_PASSWORD=SuperSecret" \
+    -d dpage/pgadmin4
+
+
+

Note that the TCP/IP port has not been mapped to the host as it was in the +Nginx example, and the container name has been set to a known value as it will +be used as the hostname and may need to be added to the DNS zone file.

+

The following configuration will listen on ports 80 and 443, redirecting 80 to +443, using the default certificate shipped with Traefik. See the Traefik +documentation for options to use certificates from LetsEncrypt or other issuers.

+
defaultEntryPoints = ["http", "https"]
+
+[entryPoints]
+  [entryPoints.http]
+    address = ":80"
+      [entryPoints.http.redirect]
+        entryPoint = "https"
+  [entryPoints.https]
+    address = ":443"
+      [entryPoints.https.tls]
+
+[docker]
+domain = "domain_name"
+watch = true
+
+
+

If you wish to host pgAdmin under a subdirectory using Traefik, the +configuration changes are typically made to the way the container is launched +and not to Traefik itself. For example, to host pgAdmin under /pgadmin4/ +instead of at the root directory, the Traefik configuration above may be used if +the container is launched like this while using the version v1 of Traefik:

+
docker pull dpage/pgadmin4
+docker run --name "pgadmin4" \
+    -e "PGADMIN_DEFAULT_EMAIL=user@domain.com" \
+    -e "PGADMIN_DEFAULT_PASSWORD=SuperSecret" \
+    -e "SCRIPT_NAME=/pgadmin4" \
+    -l "traefik.frontend.rule=PathPrefix:/pgadmin4" \
+    -d dpage/pgadmin4
+
+
+

The SCRIPT_NAME environment variable has been set to tell the container it is +being hosted under a subdirectory (in the same way as the X-Script-Name header +is used with Nginx), and a label has been added to tell Traefik to route +requests under the subdirectory to this container.

+

While using the Traefik configuration for version v2 for hosting pgAdmin under subdirectory +the container is typically launched per the example below:

+
docker pull dpage/pgadmin4
+docker run --name "pgadmin4" \
+    -e "PGADMIN_DEFAULT_EMAIL=user@domain.com" \
+    -e "PGADMIN_DEFAULT_PASSWORD=SuperSecret" \
+    -e "SCRIPT_NAME=/pgadmin4" \
+    -l "traefik.frontend.pgadmin4.rule=Host(`host.example.com`) && PathPrefix(`/pgadmin4`)" \
+    -d dpage/pgadmin4
+
+
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/contributions.html b/pgsql/pgAdmin 4/docs/en_US/html/contributions.html new file mode 100644 index 0000000000000000000000000000000000000000..f283f3781bd844dfcd7800c51c156ed98235486e --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/contributions.html @@ -0,0 +1,176 @@ + + + + + + + + + + pgAdmin Project Contributions — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

pgAdmin Project Contributions

+

pgAdmin is an open-source project that invites you to get involved in the +development process. For more information about contributing to the pgAdmin +project, contact the developers on the pgAdmin mailing list +pgadmin-hackers@postgresql.org to discuss any ideas you might have for +enhancements or bug fixes.

+

In the following sections, you’ll find detailed information about the +development process used to develop, improve, and maintain the pgAdmin client.

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/database_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/database_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..c43a59149bbaed984969b244852b42ef4ac3ec30 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/database_dialog.html @@ -0,0 +1,255 @@ + + + + + + + + + + Database Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Database Dialog

+

Use the Database dialog to define or modify a database. To create a database, +you must be a database superuser or have the CREATE privilege.

+

The Database dialog organizes the development of a database through the +following dialog tabs: General, Definition, Security, and Parameters. +The SQL tab displays the SQL code generated by dialog selections.

+Database dialog general tab +

Use the fields in the General tab to identify the database:

+
    +
  • Use the Database field to add a descriptive name for the database. The name +will be displayed in the pgAdmin tree control.

  • +
  • Use the OID field to specify the object identifier to be used for the new +database. Users can specify the value greater than 16383. This option is available +from v15 and above.

  • +
  • Select the owner of the database from the drop-down listbox in the Owner +field.

  • +
  • Store notes about the database in the Comment field.

  • +
+

Click the Definition tab to continue.

+Database dialog definition tab +

Use the Definition tab to set properties for the database:

+
    +
  • Select a character set from the drop-down listbox in the Encoding field. +The default is UTF8.

  • +
  • Select a template from the drop-down listbox in the Template field. If you +do not specify a template, the database will use template1.

  • +
  • Select a tablespace from the drop-down listbox in the Tablespace field. The +selected tablespace will be the default tablespace used to contain database +objects.

  • +
  • Select the strategy from the drop-down listbox in the Strategy field while +creating a new database. This option is available from v15 and above.

  • +
  • Select the locale provider from the drop-down listbox in the Locale Provider +field to set the default collation for this database. Possible values are: icu, libc. +This option is available from v15 and above.

  • +
  • Select the collation order from the drop-down listbox in the Collation field.

  • +
  • Select the character classification from the drop-down listbox in the +Character Type field. This affects the categorization of characters, e.g. +lower, upper and digit. The default, or a blank field, uses the character +classification of the template database.

  • +
  • Select the icu locale from the drop-down listbox in the ICU Locale to +specifies the ICU locale ID if the ICU locale provider is used. +This option is available from v15 and above.

  • +
  • Specify the icu rules in the ICU Rules field as additional collation +rules to customize the behavior of the default collation of this database. +This option is available from v16 and above.

  • +
  • Specify a connection limit in the Connection Limit field to configure the +maximum number of connection requests. The default value (-1) allows +unlimited connections to the database.

  • +
  • If the templates? is set to true, then database will be a template database.

  • +
+

Click the Security tab to continue.

+Database dialog security tab +

Use the Security tab to assign privileges and define security labels.

+

Use the Privileges panel to assign privileges to a role. Click the Add icon +(+) to set privileges for database objects:

+
    +
  • Select the name of the role from the drop-down listbox in the Grantee field.

  • +
  • Click inside the Privileges field. Check the boxes to the left of one or +more privileges to grant the selected privilege to the specified user.

  • +
  • The current user, who is the default grantor for granting the privilege, is displayed in the Grantor field.

  • +
+

Click add to set additional privileges; to discard a privilege, click the trash +icon to the left of the row and confirm deletion in the Delete Row popup.

+

Use the Security Labels panel to define security labels applied to the +database. Click the Add icon (+) to add each security label selection:

+
    +
  • Specify a security label provider in the Provider field. The named provider +must be loaded and must consent to the proposed labeling operation.

  • +
  • Specify a a security label in the Security Label field. The meaning of a +given label is at the discretion of the label provider. PostgreSQL places no +restrictions on whether or how a label provider must interpret security +labels; it merely provides a mechanism for storing them.

  • +
+

To discard a security label, click the trash icon to the left of the row and +confirm deletion in the Delete Row popup.

+

Click the Parameters tab to continue.

+Database dialog parameters tab +

Use the Parameters tab to set parameters for the database. Click the Add +icon (+) to add each parameter:

+
    +
  • Use the drop-down listbox in the Name field to select a parameter.

  • +
  • Use the Value field to set a value for the parameter.

  • +
  • Use the drop-down listbox next to Role to select a role to which the +parameter setting specified will apply.

  • +
+

Follow these steps to add additional parameter value definitions; to discard a +parameter, click the trash icon to the left of the row and confirm deletion in +the Delete Row popup.

+

Click the Advanced tab to continue.

+Database dialog advanced tab +

Use the Advanced tab to set advanced parameters for the database.

+
    +
  • Use Schema restriction field to provide a SQL restriction that will be used +against the pg_namespace table to limit the schemas that you see. +For example, you might enter: public so that only public are shown in +the pgAdmin browser.Separate entries with a comma or tab as you type.

  • +
+

Click the SQL tab to continue.

+

Your entries in the Database dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Database dialog:

+Database dialog sql tab +

The example creates a database named hr that is owned by postgres. It +allows unlimited connections, and is available to all authenticated users.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/dbms_job.html b/pgsql/pgAdmin 4/docs/en_US/html/dbms_job.html new file mode 100644 index 0000000000000000000000000000000000000000..8e6176983dc89f95f52ba238b063d0181b50c3bc --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/dbms_job.html @@ -0,0 +1,227 @@ + + + + + + + + + + DBMS Job — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

DBMS Job

+

Use the DBMS Job dialog to create a DBMS Job.

+DBMS Job dialog general tab +

Use the fields in the General tab to create job:

+
    +
  • Use the Name field to add a descriptive name for the job. The name will +be displayed in the pgAdmin object explorer.

  • +
  • Use the Enabled? switch to indicate that job should be enabled or disabled.

  • +
  • Use the Job Type field to select the type of the job. Type could be SELF-CONTAINED or PRE-DEFINED. +If the Job Type is Self-Contained you need to specify the action and repeat interval in the Action and Repeat tabs respectively. +If the Job Type is Pre-Defined you need to specify the existing Program and Schedule names in the Pre-Defined tab.

  • +
  • Store notes about the job in the Comment field.

  • +
+

Click the Action tab to continue.

+DBMS Job dialog action tab +

Use the Action tab to select the action for the job. This tab is only enabled when the job type is ‘SELF-CONTAINED’.

+
    +
  • Use the Type field to select the type of the job. Type could be PLSQL BLOCK or STORED PROCEDURE.

  • +
  • Use the Procedure field to select an existing procedure that executes when the job is invoked.

  • +
  • Number of Arguments field is read-only and indicates the quantity of arguments necessary for the chosen procedure.

  • +
+

Click the Code tab to continue.

+DBMS Job dialog code tab +
    +
  • Use the Code field to write the code that executes when the job is invoked. +This tab is only enabled when the job type is ‘SELF-CONTAINED’ and type of the action is set to ‘PLSQL BLOCK’.

  • +
+

Click the Arguments tab to continue.

+DBMS Job dialog arguments tab +
    +
  • Arguments tab outlines the arguments required by the selected procedure in the ‘Action’ tab. This tab is only enabled when the job type is ‘SELF-CONTAINED’.

  • +
+

Click the Repeat tab to continue.

+DBMS Job dialog repeat tab +

Use the Repeat tab to select the repeat interval for the job. This tab is only enabled when the job type is ‘SELF-CONTAINED’.

+
    +
  • Use the calendar selector in the Start field to specify the starting date +and time for the job.

  • +
  • Use the calendar selector in the End field to specify the ending date and +time for the job.

  • +
  • Use the Frequency field to select the frequency. Frequency is one of the following: +YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY.

  • +
  • Use the Date field to select the date on which job will execute.Date is YYYYMMDD.

  • +
  • Use the Months field to select the months in which the job will execute.

  • +
  • Use the Week Days field to select the days on which the job will execute.

  • +
  • Use the Month Days field to select the numeric days on which the job will +execute.

  • +
  • Use the Hours field to select the hour at which the job will execute.

  • +
  • Use the Minutes field to select the minute at which the job will execute.

  • +
+

Click the Pre-Defined tab to continue.

+DBMS Job dialog predefined tab +

Use the Pre-Defined tab to select the existing program and schedule to create the job. +This tab is only enabled when the job type is ‘PRE-DEFINED’.

+
    +
  • Use the Program Name field to select the existing program.

  • +
  • Use the Schedule Name field to select an existing schedule.

  • +
+

Click the SQL tab to continue.

+

Your entries in the DBMS Job dialog generate a SQL command (see an example below). +Use the SQL tab for review; revisit or switch tabs to make any changes to the +SQL command.

+

Example

+

The following is an example of the sql command generated by user selections in +the DBMS Job dialog:

+DBMS Job dialog sql tab +
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Help button (?) to access dialog help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/dbms_job_scheduler.html b/pgsql/pgAdmin 4/docs/en_US/html/dbms_job_scheduler.html new file mode 100644 index 0000000000000000000000000000000000000000..9f868c3b18d52d7c4f6d29e3638d59a27fa75490 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/dbms_job_scheduler.html @@ -0,0 +1,191 @@ + + + + + + + + + + Using EDB Job Scheduler — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Using EDB Job Scheduler

+

In the past versions of EPAS, DBMS_SCHEDULER or DBMS_JOBS required the configuration +of pgAgent, an essential service for their functionality. Maintaining pgAgent in a +production environment is cumbersome. The need for correct configuration, regular updates, +and ensuring the service’s health added complexity.

+

EPAS 16 revolutionizes job scheduling by eliminating the need for the pgAgent component. +The new version introduces EDB Job Scheduler which is an extension that runs the job scheduler +as a background process for the DBMS_SCHEDULER and DBMS_JOB packages.

+

The EDB Job Scheduler has a scheduler process that starts when the database cluster starts. +To start the scheduler process, load the EDB Job Scheduler extension using the shared_preload_libraries +parameter. After you load the extension, create the extension ‘edb_job_scheduler’ and ‘dbms_scheduler’ using +the CREATE EXTENSION command. The database in which you’re creating the extension must be listed in the +edb_job_scheduler.database_list parameter.

+

Instructions for configuring the EDB Job Scheduler can be found in the +Configuring EDB Job Scheduler.

+DBMS Job Scheduler Object Browser +
+

Check the status of all the jobs

+

To check the running status of all the jobs select the ‘DBMS Job Scheduler’ collection node from the object +explorer and select the Properties tab.

+DBMS Job Details + +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/dbms_program.html b/pgsql/pgAdmin 4/docs/en_US/html/dbms_program.html new file mode 100644 index 0000000000000000000000000000000000000000..70cefd5c62feedb8e9d1d2e1d136168f503fdec4 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/dbms_program.html @@ -0,0 +1,198 @@ + + + + + + + + + + DBMS Program — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

DBMS Program

+

Use the DBMS Program dialog to create a DBMS Program.

+DBMS Program dialog general tab +

Use the fields in the General tab to create program:

+
    +
  • Use the Name field to add a descriptive name for the program. The name will +be displayed in the pgAdmin object explorer.

  • +
  • Use the Enabled? switch to indicate that program should be enabled or disabled.

  • +
  • Store notes about the program in the Comment field.

  • +
+

Click the Action tab to continue.

+DBMS Program dialog action tab +

Use the Action tab to select the action for the program:

+
    +
  • Use the Type field to select the type of the program. Type could be PLSQL BLOCK or STORED PROCEDURE.

  • +
  • Use the Procedure field to select an existing procedure that executes when the program is invoked.

  • +
  • Number of Arguments field is read-only and indicates the quantity of arguments necessary for the chosen procedure.

  • +
+

Click the Code tab to continue.

+DBMS Program dialog code tab +
    +
  • Use the Code field to write the code that executes when the program is invoked. +This tab is only enabled when the type of the program is set to ‘PLSQL BLOCK’.

  • +
+

Click the Arguments tab to continue.

+DBMS Program dialog arguments tab +
    +
  • Arguments tab is a read-only section that outlines the arguments required by the selected procedure in the ‘Action’ tab.

  • +
+

Click the SQL tab to continue.

+

Your entries in the DBMS Program dialog generate a SQL command (see an example below). +Use the SQL tab for review; revisit or switch tabs to make any changes to the +SQL command.

+

Example

+

The following is an example of the sql command generated by user selections in +the DBMS Program dialog:

+DBMS Program dialog sql tab +
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Help button (?) to access dialog help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/dbms_schedule.html b/pgsql/pgAdmin 4/docs/en_US/html/dbms_schedule.html new file mode 100644 index 0000000000000000000000000000000000000000..a6c5e8f9cf00c2f1990662a224ffcaf4503c0d26 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/dbms_schedule.html @@ -0,0 +1,196 @@ + + + + + + + + + + DBMS Schedule — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

DBMS Schedule

+

Use the DBMS Schedule dialog to create a DBMS Schedule.

+DBMS Schedule dialog general tab +

Use the fields in the General tab to create schedule:

+
    +
  • Use the Name field to add a descriptive name for the schedule. The name will +be displayed in the pgAdmin object explorer.

  • +
  • Store notes about the schedule in the Comment field.

  • +
+

Click the Repeat tab to continue.

+DBMS Schedule dialog repeat tab +

Use the Repeat tab to select the repeat interval for the schedule:

+
    +
  • Use the calendar selector in the Start field to specify the starting date +and time for the schedule.

  • +
  • Use the calendar selector in the End field to specify the ending date and +time for the schedule.

  • +
  • Use the Frequency field to select the frequency. Frequency is one of the following: +YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY.

  • +
  • Use the Date field to select the date on which schedule will execute.Date is YYYYMMDD.

  • +
  • Use the Months field to select the months in which the schedule will execute.

  • +
  • Use the Week Days field to select the days on which the schedule will execute.

  • +
  • Use the Month Days field to select the numeric days on which the schedule will +execute.

  • +
  • Use the Hours field to select the hour at which the schedule will execute.

  • +
  • Use the Minutes field to select the minute at which the schedule will execute.

  • +
+

Click the SQL tab to continue.

+

Your entries in the DBMS Schedule dialog generate a SQL command (see an example below). +Use the SQL tab for review; revisit or switch tabs to make any changes to the +SQL command.

+

Example

+

The following is an example of the sql command generated by user selections in +the DBMS Schedule dialog:

+DBMS Schedule dialog sql tab +
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Help button (?) to access dialog help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/debugger.html b/pgsql/pgAdmin 4/docs/en_US/html/debugger.html new file mode 100644 index 0000000000000000000000000000000000000000..ecac4c46869379287e95113b85c408b24ce9bb45 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/debugger.html @@ -0,0 +1,278 @@ + + + + + + + + + + Debugger — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Debugger

+Debugger page +

The debugger may be used to debug PL/pgSQL functions in PostgreSQL, as well as +EDB-SPL functions, stored procedures and packages in EDB Postgres Advanced +Server. The Debugger is available as an extension for your PostgreSQL +installation, and is distributed as part of Advanced Server. You must have +superuser privileges to use the debugger.

+

Before using the debugger, you must modify the postgresql.conf file, adding +the server-side debugger components to the value of the +shared_preload_libraries parameter, for example:

+
+

shared_preload_libraries = ‘$libdir/plugin_debugger’

+
+

After modifying the shared_preload_libraries parameter, restart the server to +apply the changes.

+

The debugger may be used for either in-context debugging or direct debugging of +a target function or procedure. When you use the debugger for in-context +debugging, you set a breakpoint at the first line of a program; when a session +invokes the target, control is transferred to the debugger. When using direct +debugging, the debugger prompts you for any parameters required by the target, +and then allows you to step through the code.

+
+

In-context Debugging

+

To set a breakpoint at the first line of a program, right-click the name of the +object you would like to debug, and select Set breakpoint from the Debugging +sub-menu. The debugger window will open, waiting for another session to invoke +the program.

+Debugger set a breakpoint demo +

When another session invokes the target, the debugger will display the code, +allowing you to add break points, or step through line-by-line. The other +session is suspended until the debugging completes; then control is returned +to the session.

+Debugger step-in demo +
+
+

Direct Debugging

+

To use the debugger for direct debugging, right click on the name of the object +that you wish to debug in the pgAdmin tree control and select Debug from the +Debugging sub-menu. The debugger window will open, prompting you for any +values required by the program:

+Debugger parameter dialog +

Use the fields on the Debugger dialog to provide a value for each parameter:

+
+
    +
  • The Name field contains the formal parameter name.

  • +
  • The Type field contains the parameter data type.

  • +
  • Check the Null? checkbox to indicate that the parameter is a NULL value.

  • +
  • Check the Expression? checkbox if the Value field contains an expression.

  • +
  • Use the Value field to provide the parameter value that will be passed to +the program. When entering parameter values, type the value into the +appropriate cell on the grid, or, leave the cell empty to represent NULL, +enter ‘’ (two single quotes) to represent an empty string, or to enter a +literal string consisting of just two single quotes, enter ''. PostgreSQL +8.4 and above supports variadic function parameters. These may be entered as +a comma-delimited list of values, quoted and/or cast as required.

  • +
  • Check the Use default? checkbox to indicate that the program should use +the value in the Default Value field.

  • +
  • The Default Value field contains the default value of the parameter.

  • +
+
+

Provide values required by the program, and click the Debug button to start +stepping through the program. +The values of the arguments provided here are saved. The values will be pre-filled +next time the dialog opens. To clear the values, use the Clear All button.

+Debugger step-in demo +
+
+

Using the Debugger

+

The main debugger window consists of two panels and a context-sensitive toolbar. +Use toolbar icons to manage breakpoints and step into or through code; hover +over an icon for a tooltip that identifies the option associated with the icon. +The toolbar options are:

+Debugger navigation toolbar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Option

Action

Step into

Click the Step into icon to execute the currently highlighted line of code.

Step over

Click the Step over icon to execute a line of code, stepping over any sub-functions invoked by the code. +The sub-function executes, but is not debugged unless it contains a breakpoint.

Continue/Start

Click the Continue/Start icon to execute the highlighted code, and continue until the program +encounters a breakpoint or completes.

Toggle breakpoint

Use the Toggle breakpoint icon to enable or disable a breakpoint (without removing the breakpoint).

Clear all breakpoints

Click the Clear all breakpoints icon to remove all breakpoints from the program.

Stop

Click the Stop icon to halt the execution of a program.

Help

Click the Help icon to open debugger documentation.

+

The top panel of the debugger window displays the program body; click in the +grey margin next to a line number to add a breakpoint. The highlighted line in +the top panel is the line that is about to execute.

+Debugger main window +

The lower panel of the debugger window provides a set of tabs that allow you to +review information about the program:

+
+
    +
  • The Parameters tab displays the value of each parameter.

  • +
  • The Local variables tab displays the current value of the program variables.

  • +
  • The Messages tab displays any messages returned by the server (errors, +warnings and informational messages).

  • +
  • The Results tab displays the server message when the program completes.

  • +
  • The Stack tab displays the list of functions that have been invoked, but +which have not yet completed.

  • +
+
+

As you step through a program, the Local variables tab displays the current +value of each variable:

+Debugger local variables tab +

When you step into a subroutine, the Stack tab displays the call stack, +including the name of each caller, the parameter values for each caller (if +any), and the line number within each caller:

+Debugger local stack tab +

Select a caller to change focus to that stack frame and display the state of +the caller in the upper panel.

+

When the program completes, the Results tab displays the message returned by +the server. If the program encounters an error, the Messages tab displays +details:

+Debugger error message +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/deployment.html b/pgsql/pgAdmin 4/docs/en_US/html/deployment.html new file mode 100644 index 0000000000000000000000000000000000000000..684b001bd2df41d537c2ccfec6ff3493e9a25998 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/deployment.html @@ -0,0 +1,172 @@ + + + + + + + + + + Deployment — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Deployment

+

Pre-compiled and configured installation packages for pgAdmin 4 are available +for a number of desktop environments; we recommend using an installer whenever +possible. If you are interested in learning more about the project, or if a +pgAdmin installer is not available for your environment, the pages listed below +will provide detailed information about creating a custom deployment.

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/desktop_deployment.html b/pgsql/pgAdmin 4/docs/en_US/html/desktop_deployment.html new file mode 100644 index 0000000000000000000000000000000000000000..f5f9a347c7e1675b560247f861885295055b72d0 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/desktop_deployment.html @@ -0,0 +1,298 @@ + + + + + + + + + + Desktop Deployment — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Desktop Deployment

+

pgAdmin may be deployed as a desktop application by configuring the application +to run in desktop mode and then utilising the desktop runtime to host the +program on a supported Windows, Mac OS X or Linux installation.

+

The desktop runtime is a standalone application that when launched, runs the +pgAdmin server and opens a window to render the user interface.

+
+

Note

+

Pre-compiled and configured installation packages are available for +a number of platforms. These packages should be used by end-users whereever +possible - the following information is useful for the maintainers of those +packages and users interested in understanding how pgAdmin works.

+
+
+

See also

+

For detailed instructions on building and configuring pgAdmin from +scratch, please see the README file in the top level directory of the source code. +For convenience, you can find the latest version of the file +here, +but be aware that this may differ from the version included with the source code +for a specific version of pgAdmin.

+
+
+

Configuration

+

From pgAdmin 4 v2 onwards, the default configuration mode is server, however, +this is overridden by the desktop runtime at startup. In most environments, no +Python configuration is required unless you wish to override other default +settings.

+

See The config.py File for more information on configuration settings.

+
+

Desktop Runtime Standalone Application

+

The Desktop Runtime is based on NWjs which integrates a +browser and the Python server creating a standalone application.

+Runtime Standalone +
+

Runtime Menu

+Runtime Menu +

Use the File Menu to access the Runtime Menu:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +

Option

Action

Configure…

Click to open configuration dialog to configure fixed port, port number and connection timeout.

View log…

Click to open the view log dialog to view the pgAdmin 4 logs.

Enter Full Screen

Click to enter/exit the full screen mode. Keyboard Shortcuts: OSX (Cmd + Ctrl + F), Other OS (F10).

Actual Size

Click to change the window size to it original size. Keyboard Shortcuts: OSX (Cmd + 0), +Other OS (Ctrl + 0).

Zoom In

Click to increase the zoom level. Keyboard Shortcuts: OSX (Cmd + +), Other OS (Ctrl + +).

Zoom Out

Click to decrease the zoom level. Keyboard Shortcuts: OSX (Cmd + -), Other OS (Ctrl + -).

+
+
+

Configuration Dialog

+

Use the Runtime Menu to access the Configuration dialog:

+Runtime Configuration +

Following are the details of the Fixed port number?, Port Number, Connection +Timeout, and ‘Open Documentation in Default Browser?’ configuration parameters:

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +

Key

Type

Purpose

FixedPort

Boolean

Use a fixed network port number rather than a random one.

PortNumber

Integer

The port number to use, if using a fixed port.

ConnectionTimeout

Integer

The number of seconds to wait for application server startup.

Open Documentation in Default Browser

Boolean

By checking this option, all documentation links will open in +the default browser instead of in a new window.

+
+
+

Log dialog

+

Use the Runtime Menu to access the Log dialog:

+Runtime View Log +

Click on the Reload button at the bottom to view the latest logs of pgAdmin 4 +Server.

+

When executed, the runtime will automatically try to execute the pgAdmin Python +application. If execution fails, it will prompt you with error message +displaying a Configure button at the bottom. You can configure a fixed port +number to avoid clashes of the default random port number with other +applications and a connection timeout if desired.

+Runtime Error +

If the error is related to Python Path or pgAdmin Python file then you need to +create a file named ‘dev_config.json’ and specify the following entries:

+
{
+    "pythonPath": "/path/to/python.exe",
+    "pgadminFile": "/path/to/pgAdmin4.py"
+}
+
+
+

Note that the dev_config.py file should only be required by developers who are +working outside of a standard installation.

+

The configuration settings are stored in runtime_config.json file, which +will be available on Unix systems (~/.local/share/pgadmin/), +on Mac OS X (~/Library/Preferences/pgadmin), +and on Windows (%APPDATA%/pgadmin).

+
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/developer_tools.html b/pgsql/pgAdmin 4/docs/en_US/html/developer_tools.html new file mode 100644 index 0000000000000000000000000000000000000000..a94b5b3c580cf8d0f2ee3b39e856b327b6225dae --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/developer_tools.html @@ -0,0 +1,186 @@ + + + + + + + + + + Developer Tools — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+ +
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/domain_constraint_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/domain_constraint_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..18941aa3f678ef0611deff98139c4dfe56e5f166 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/domain_constraint_dialog.html @@ -0,0 +1,210 @@ + + + + + + + + + + Domain Constraints Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Domain Constraints Dialog

+

Use the Domain Constraints dialog to create or modify a domain constraint. A +domain constraint confirms that the values provided for a domain meet a defined +criteria. The Domain Constraints dialog implements options of the ALTER DOMAIN +command.

+

The Domain Constraints dialog organizes the development of a domain constraint +through the following dialog tabs: General and Definition. The SQL tab +displays the SQL code generated by dialog selections.

+Domain constraint dialog general tab +

Use the fields in the General tab to identify the domain constraint:

+
    +
  • Use the Name field to add a descriptive name for the constraint. The name +will be displayed in the pgAdmin tree control.

  • +
  • Store notes about the constraint in the Comment field.

  • +
+

Click the Definition tab to continue.

+Domain constraint dialog general tab +

Use the fields in the Definition tab to define the domain constraint:

+
    +
  • Use the Check field to provide a CHECK expression. A CHECK expression +specifies a constraint that the domain must satisfy. A constraint must produce +a Boolean result; include the key word VALUE to refer to the value being +tested. Only those expressions that evaluate to TRUE or UNKNOWN will succeed. +A CHECK expression cannot contain subqueries or refer to variables other than +VALUE. If a domain has multiple CHECK constraints, they will be tested in +alphabetical order.

  • +
  • Move the Validate? switch to the No position to mark the constraint NOT +VALID. If the constraint is marked NOT VALID, the constraint will not be +applied to existing column data. The default value is Yes.

  • +
+

Click the SQL tab to continue.

+

Your entries in the Domain Constraints dialog generate a SQL command (see an +example below). Use the SQL tab for review; revisit or switch tabs to make any +changes to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Domain Constraints dialog:

+Domain constraint dialog general tab +

The example shown demonstrates creating a domain constraint on the domain +timesheets named weekday. It constrains a value equal to Friday.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/domain_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/domain_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..e05c278969c9cd4440d64b44802748bde9667ad5 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/domain_dialog.html @@ -0,0 +1,255 @@ + + + + + + + + + + Domain Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Domain Dialog

+

Use the Domain dialog to define a domain. A domain is a data type definition +that may constrain permissible values. Domains are useful when you are creating +multiple tables that contain comparable columns; you can create a domain that +defines constraints that are common to the columns and re-use the domain +definition when creating the columns, rather than individually defining each +set of constraints.

+

The Domain dialog organizes the development of a domain through the following +tabs: General, Definition, Constraints, and Security. The SQL tab +displays the SQL code generated by dialog selections.

+Domain dialog general tab +

Use the fields on the General tab to identify a domain:

+
    +
  • Use the Name field to add a descriptive name for the domain. The name will +be displayed in the pgAdmin tree control.

  • +
  • Use the drop-down listbox next to Owner to select a role that will own the +domain.

  • +
  • Select the name of the schema in which the domain will reside from the +drop-down listbox in the Schema field.

  • +
  • Store notes about the domain in the Comment field.

  • +
+

Click the Definition tab to continue.

+Domain dialog definition tab +

Use the fields in the Definition tab to describe the domain:

+
    +
  • Use the drop-down listbox next to Base type to specify a data type.

  • +
  • Use the context-sensitive Length field to specify a numeric length for a +numeric type.

  • +
  • Use the context-sensitive Precision field to specify the total count of +significant digits for a numeric type.

  • +
  • Specify a default value for the domain data type in the Default field. The +data type of the default expression must match the data type of the domain. If +no default value is specified, then the default value is the null value.

  • +
  • Move the Not Null switch to specify the values of this domain are prevented +from being null.

  • +
  • Use the drop-down listbox next to Collation to apply a collation cast. If +no collation is specified, the underlying data type’s default collation is +used. The underlying type must be collatable if COLLATE is specified.

  • +
+

Click the Constraints tab to continue.

+Domain dialog constraints tab +

Use the fields in the Constraints tab to specify rules for the domain. Click +the Add icon (+) to set constraints:

+
    +
  • Use the Name field to specify a name for the constraint.

  • +
  • Use the Check field to provide an expression for the constraint.

  • +
  • Use the Validate checkbox to determine whether the constraint will be +validated. The default checkbox is checked and sets a validation requirement.

  • +
+

A CHECK clause specifies an integrity test which values of the domain must +satisfy. Each constraint must be an expression that produces a Boolean result. +Use the key word VALUE to refer to the value being tested. Expressions +evaluating to TRUE or UNKNOWN succeed. If the expression produces a FALSE +result, an error is reported and the value is not allowed to be converted to +the domain type. A CHECK expression cannot contain subqueries nor refer to +variables other than VALUE. If a domain has multiple CHECK constraints, they +will be tested in alphabetical order by name.

+

Click the Add icon (+) to set additional constraints; to discard a constraint, +click the trash icon to the left of the row and confirm deletion in the Delete +Row popup.

+

Click the Security tab to continue.

+Domain dialog security tab +

Use the Security Labels panel to assign security labels. Click the Add icon +(+) to add a label:

+
    +
  • Specify a security label provider in the Provider field. The named provider +must be loaded and must consent to the proposed labeling operation.

  • +
  • Specify a a security label in the Security Label field. The meaning of a +given label is at the discretion of the label provider. PostgreSQL places no +restrictions on whether or how a label provider must interpret security +labels; it merely provides a mechanism for storing them.

  • +
+

Click the Add icon (+) to specify each additional label; to discard a label, +click the trash icon to the left of the row and confirm deletion in the Delete +Row popup.

+

Click the SQL tab to continue.

+

Your entries in the Domain dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by selections made in +the Domain dialog:

+Domain dialog sql tab +

The example shown demonstrates creating a domain named postal_code that +confirms that the value entered is in proper format.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/editgrid.html b/pgsql/pgAdmin 4/docs/en_US/html/editgrid.html new file mode 100644 index 0000000000000000000000000000000000000000..6ded7258157b974e9c19686a42b0c8c8625f0708 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/editgrid.html @@ -0,0 +1,341 @@ + + + + + + + + + + View/Edit Data — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

View/Edit Data

+

To view or modify data, right click on a table or view name in the +Object Explorer. When the context menu opens, use the View/Edit Data menu +to specify the number of rows you would like to display in the editor panel.

+Edit grid window +

To modify the content of a table, each row in the table must be uniquely +identifiable. If the table definition does not include an OID or a primary key, +the displayed data is read only. Note that views cannot be edited; updatable +views (using rules) are not supported.

+

The editor features a toolbar that allows quick access to frequently used +options, and a work environment divided into two panels:

+
    +
  • The upper panel displays the SQL command that was used to select the content +displayed in the lower panel.

  • +
  • The lower panel (the Data Grid) displays the data selected from the table or +view.

  • +
+
+

The View/Edit Data Toolbar

+

The Query Tool and View/Edit Data tools +are actually different operating modes of the same tool. Some controls will be +disabled in either mode. Please see +The Query Tool Toolbar for a description of the +available controls.

+
+
+

The Data Grid

+

The top row of the data grid displays the name of each column, the data type, +and if applicable, the number of characters allowed. A column that is part of +the primary key will additionally be marked with [PK].

+

To modify the displayed data:

+
    +
  • To change a numeric value within the grid, double-click the value to select +the field. Modify the content in the square in which it is displayed.

  • +
  • To change a non-numeric value within the grid, double-click the content to +access the edit bubble. After modifying the contentof the edit bubble, click +the Ok button to display your changes in the data grid, or Cancel to +exit the edit bubble without saving.

  • +
+

To enter a newline character, click Ctrl-Enter or Shift-Enter. Newline +formatting is only displayed when the field content is accessed via an edit +bubble.

+

To add a new row to the table, enter data into the last (unnumbered) row of the +table. As soon as you store the data, the row is assigned a row number, and a +fresh empty line is added to the data grid.

+

To write a SQL NULL to the table, simply leave the field empty. When you store +the new row, the will server fill in the default value for that column. If you +store a change to an existing row, the value NULL will explicitly be written.

+

To write an empty string to the table, enter the special string ‘’ (two single +quotes) in the field. If you want to write a string containing solely two single +quotes to the table, you need to escape these quotes, by typing ''

+

To delete a row, press the Delete toolbar button. A popup will open, asking +you to confirm the deletion.

+

To commit the changes to the server, select the Save Data toolbar button.

+

Geometry Data Viewer

+

If PostGIS is installed, you can view GIS objects in a map by selecting row(s) +and clicking the ‘View Geometry’ button in the column. If no rows are selected, +the entire data set will be rendered:

+Geometry Viewer Button +

You can adjust the layout by dragging the title of the panel. To view the +properties of the geometries directly in map, just click the specific geometry:

+Geometry Viewer Property Table +
+

Note

+
    +
  • Supported data types: The Geometry Viewer supports 2D and 3DM geometries in +EWKB format including Point, LineString, Polygon MultiPoint, MultiLineString, +MultiPolygon and GeometryCollection.

  • +
  • SRIDs: If there are geometries with different SRIDs in the same column, the +viewer will render geometries with the same SRID in the map. If SRID=4326 the +OSM tile layer will be added into the map.

  • +
  • Data size: For performance reasons, the viewer will render no more than +100000 geometries, totaling up to 20MB.

  • +
  • Internet access: An internet connection is required for the Geometry Viewer +to function correctly.

  • +
+
+

JSON Data Editor

+

A built in json editor is provided for JSON/JSONB Data.Double clicking on json/jsonb +data type cell in data grid will open JSON Editor.Editor provides different mode to +view and edit json data.

+Json Editor +

Code Mode: +Provides way to format & compact json data.Also provides ability to repair json data +by fixing quotes and escape characters, removing comments and JSONP notation and +turn JavaScript objects into JSON.

+

Tree Mode: +Enabled to change, add, move, remove, and duplicate fields and values.Provides ability +to searh & hilight data.

+

Form Mode: +Allows only to edit values in json data there by providing ability to keep data structure +unchanged while editing.

+

Preview Mode: +Provides ability to check data before saving and also shows size of current json data. +Format and compact json data as well.

+

Editor Toolbar

+

Different options are provided to manipulate json data.

+

Code/Preview mode:

+Json Editor Code/Preview mode Tool Bar +

Tree/Form mode:

+Json Editor Tree/Form mode Tool Bar + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Icon

Behavior

Available in mode

Format Json

Click to Format Json format json data with proper indentation.

Code, Preview

Compact Json

Click to Compact Json get compacted json data.

Code, Preview

Sort

Click to Sort icon to set sorting criteria for the data using file values.

Code, Preview, Tree

Transform

Click to Transform to filter data using JSME query language.

Code, Preview, Tree

Undo

Click to Undo to undo last action performed on data .

Code, Preview, Tree, From

Redo

Click to Redo to repat last action performed on data .

Code, Preview, Tree, From

Mode

Click to Mode dropdown to change dipaly mode of editor.Different modes avaialble +are Code, Preview, Tree, From.

Code, Tree, From, Preview

Expand All

Click to Expand All to expand json data.

Tree, From

Collapse All

Click to Redo to collapse json data.

Tree, From

Search Box

Enter partial/complete string to search in data.

Tree, From

+
+
+

Sort/Filter options dialog

+

You can access Sort/Filter options dialog by clicking on Sort/Filter button. +This allows you to specify an SQL Filter to limit the data displayed and data +sorting options in the edit grid window:

+Edit grid filter dialog window +
    +
  • Use SQL Filter to provide SQL filtering criteria. These will be added to +the “WHERE” clause of the query used to retrieve the data. For example, +you might enter:

  • +
+
id > 25 AND created > '2018-01-01'
+
+
+
    +
  • Use Data Sorting to sort the data in the output grid

  • +
+

To add new column(s) in data sorting grid, click on the [+] icon.

+
    +
  • Use the drop-down Column to select the column you want to sort.

  • +
  • Use the drop-down Order to select the sort order for the column.

  • +
+

To delete a row from the grid, click the trash icon.

+
    +
  • Click the Save button to save work.

  • +
  • Click the Close button to discard current changes and close the dialog.

  • +
+ +
+
+

Promote View/Edit Data to Query Tool

+

A View/Edit Data tab can be converted to a Query Tool Tab just by editing the query. Once you start editing, it will ask if you really want to move away from View/Edit.

+Promote View/Edit Data tab to Query Tool tab warning +

You can disable the dialog by selecting the “Don’t Ask again” checkbox. If you wish to resume the confirmation dialog, you can do it from “Prefrences -> Query Tool -> Editor -> Show View/Edit Data Promotion Warning?”

+

Once you chose to continue, you won’t be able to use the features of View/Edit mode like the filter and sorting options, limit, etc. It is a one-way conversion. It will be a query tool now.

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/erd_tool.html b/pgsql/pgAdmin 4/docs/en_US/html/erd_tool.html new file mode 100644 index 0000000000000000000000000000000000000000..a7db98e4b743663f6dd6d71b3b3b2471e15444a2 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/erd_tool.html @@ -0,0 +1,481 @@ + + + + + + + + + + ERD Tool — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

ERD Tool

+

The Entity-Relationship Diagram (ERD) tool is a database design tool that provides a graphical representation of database tables, columns, and inter-relationships. ERD can give sufficient information for the database administrator to follow when developing and maintaining the database. The ERD Tool allows you to:

+
    +
  • Design and visualize the database tables and their relationships.

  • +
  • Add notes to the diagram.

  • +
  • Auto-align the tables and links for cleaner visualization.

  • +
  • Save the diagram and open it later to continue working on it.

  • +
  • Generate ready to run SQL from the database design.

  • +
  • Generate the database diagram for an existing database.

  • +
  • Drag and drop tables from object explorer to the diagram.

  • +
+ERD tool window +

You can open multiple copies of the ERD tool in individual tabs simultaneously. +You can also generate an ERD from a database, schema or a table.

+
    +
  • The ERD for database will fetch all the tables from all the schemas of the database and plot them with foreign key links.

  • +
  • The ERD for schema will fetch all the tables from a schema and plot them with foreign key links. If any table refers to a table in another +schema, then that link/foreign key will be removed.

  • +
  • The ERD for table will fetch all the tables linked directly or indirectly to mentioned table. You can change the depth of traversal from Preferences.

  • +
+
+

Toolbar

+

The ERD Tool toolbar uses context-sensitive icons that provide shortcuts to frequently performed tasks. The option is enabled for the highlighted icon and is disabled for the grayed-out icon.

+ERD tool toolbar +

Hover over an icon on Toolbar to display a tooltip that describes the icon’s functionality.

+
+
+

File Options

+ +++++ + + + + + + + + + + + + + + + + + + + + +

Icon

Behavior

Shortcut

Open File

Click the Open File icon to load a previously saved diagram.

Ctrl + O

Save

Click the Save icon to perform a quick-save of a previously saved diagram, or to save the +diagram to a file.

Ctrl + S

Save as

Click the Save As to open a new browser dialog and specify a new location to save the diagram. +You need to click the down arrow beside the save button to see Save As.

Ctrl + Shift + +S

+
+
+

Export Options

+ +++++ + + + + + + + + + + + + + + + + +

Icon

Behavior

Shortcut

Generate SQL

Click the Generate SQL icon to generate the DDL SQL for the diagram and open a query tool +with the generated SQL ready for execution. +You can select the option With DROP Table if you wish to have DROP Table DDL statements before +each CREATE Table DDL. You can see the option by clicking the down arrow beside the SQL button.

Option + Ctrl + +S

Download image

Click the Download image icon to save the ERD diagram in a image formate

Option + Ctrl + +I

+
+
+

Editing Options

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +

Icon

Behavior

Shortcut

Add table

Click this button to add a new table to the diagram. On clicking, this will open a table dialog +where you can put the table details.

Option/Alt + +Ctrl + A

Edit table

Click this button to edit a table on the diagram. On clicking, this will open a table dialog +where you can change table details. This will enable when a table is selected.

Option/Alt + +Ctrl + E

Clone table

Click this button to clone the complete table structure, name it with a auto generated name and +put it in the diagram.

Option/Alt + +Ctrl + C

Drop table/link

You can drop a table or link using this button. You need to select a table or link and click on +this button to drop it.

Option/Alt + +Ctrl + D

+
+
+

Table Relationship Options

+ +++++ + + + + + + + + + + + + + + + + +

Icon

Behavior

Shortcut

1M

Click this button to open a one-to-many relationship dialog to add a relationship between the +two tables. The selected table becomes the referencing table and will have the many endpoint of +the link.

Option/Alt + +Ctrl + O

MM

Click this button to open a many-to-many relationship dialog to add a relationship between the +two tables. This option will create a new table based on the selected columns for the two relating +tables and link them.

Option/Alt + +Ctrl + M

+
+
+

Node Color Options

+ ++++ + + + + + + + + + + + + + +

Icon

Behavior

Fill Color

Use Fill Color to change the background color of a table node. This is helpful if you want to +identify a of group tables. Once set, all the newly added tables will take the same color.

Text Color

Use Text Color to change the text color of a table node based on the fill color to make text +easily readable.

+
+
+

Utility Options

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +

Icon

Behavior

Shortcut

Add/Edit note

Click this button to make notes on tables nodes while designing the database.

Option/Alt + +Ctrl + N

Auto align

Click this button to auto align all tables and links to make it look more cleaner.

Option/Alt + +Ctrl + L

Show details

Click this button to toggle the column details visibility. It allows you to show few or more +column details.

Option/Alt + +Shift + D

Cardinality Notation

Change the cardinality notation format used to present relationship links. Options available +are - Crow’s Foot Notation and Chen Notation.

+
+
+

Zoom Options

+ +++++ + + + + + + + + + + + + + + + + + + + + +

Icon

Behavior

Shortcut

Zoom to fit

Click this button to zoom in/out automatically and fit all the tables to the view.

Option/Alt + +Shift + F

Zoom in

Click this button to zoom in the diagram.

Option/Alt + +Shift + “+”

Zoom out

Click this button to zoom out the diagram.

Option/Alt + +Shift + “-”

+
+
+

Table Dialog

+ERD tool table dialog +

The table dialog allows you to:

+
    +
  • Change the table structure details.

  • +
  • It can be used edit an existing table or add a new one.

  • +
  • Refer table dialog for information on different fields.

  • +
+
+
+

Table Node

+ERD tool table node +

The table node shows table details in a graphical representation:

+
    +
  • The top bar has a details toggle button that is used to toggle column details visibility. There is also a note button that is visible only if there is some note added. you can click on this button to quickly change the note.

  • +
  • The first row shows the schema name of the table. Eg. public in above image.

  • +
  • The second row shows the table name. Eg. users in above image.

  • +
  • All other rows below the table name are the columns of the table along with data type. If the column is a primary key then it will have lock key icon eg. id is the primary key in above image. Otherwise, it will have column icon.

  • +
  • you can click on the node and drag to move on the canvas.

  • +
  • Upon double click on the table node or by clicking the edit button from the toolbar, the table dialog opens where you can change the table details. Refer table dialog for information on different fields.

  • +
+
+ + + +
+

The Table Notes

+ERD tool table note +
    +
  • You can use the notes popup to mark some notes while designing the database.

  • +
  • You open the pop-up using the toolbar note button.

  • +
  • If some note is added to a table then it will have notes button on the table node. You can click on the button to check/update notes.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/event_trigger_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/event_trigger_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..5afe6fc6429397c5dad54883473b8ca17473fbb0 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/event_trigger_dialog.html @@ -0,0 +1,228 @@ + + + + + + + + + + Event Trigger Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Event Trigger Dialog

+

Use the Event Trigger dialog to define an event trigger. Unlike regular +triggers, which are attached to a single table and capture only DML events, +event triggers are global to a particular database and are capable of capturing +DDL events. Like regular triggers, event triggers can be written in any +procedural language that includes event trigger support, or in C, but not in +SQL.

+

The Event Trigger dialog organizes the development of a event trigger through +the following dialog tabs: General, Definition, and Security Labels. The +SQL tab displays the SQL code generated by dialog selections.

+Event trigger dialog general tab +

Use the fields in the General tab to identify the event trigger:

+
    +
  • Use the Name field to add a descriptive name for the event trigger. The name +will be displayed in the pgAdmin tree control.

  • +
  • Use the drop-down listbox next to Owner to specify the owner of the event +trigger.

  • +
  • Store notes about the event trigger in the Comment field.

  • +
+

Click the Definition tab to continue.

+Event trigger dialog definition tab +

Use the fields in the Definition tab to define the event trigger:

+
    +
  • Select a value from the drop down of Trigger Enabled field to specify a status +for the trigger: Enable Disable, Replica Always.

  • +
  • Use the drop-down listbox next to Trigger function to specify an existing +function. A trigger function takes an empty argument list, and returns a +value of type event_trigger.

  • +
  • Select a value from the drop down of Events field to specify when the event +trigger will fire: DDL COMMAND START, DDL COMMAND END, or SQL DROP.

  • +
  • Use the When TAG in field to enter filter values for TAG for which the trigger +will be executed. The values must be in single quotes separated by comma.

  • +
+

Click the Security Labels tab to continue.

+Event trigger dialog security tab +

Use the Security tab to define security labels applied to the trigger. Click +the Add icon (+) to add each security label.

+
    +
  • Specify a security label provider in the Provider field. The named provider +must be loaded and must consent to the proposed labeling operation.

  • +
  • Specify a security label in the Security Label field. The meaning of a given +label is at the discretion of the label provider. PostgreSQL places no +restrictions on whether or how a label provider must interpret security +labels; it merely provides a mechanism for storing them.

  • +
+

Click the Add icon (+) to assign additional security labels; to discard a +security label, click the trash icon to the left of the row and confirm deletion +in the Delete Row popup.

+

Click the SQL tab to continue.

+

Your entries in the Event Trigger dialog generate a generate a SQL command. +Use the SQL tab for review; revisit or switch tabs to make any changes to the +SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Event Trigger dialog:

+Event trigger dialog sql tab +

The command creates an event trigger named accounts that invokes the procedure +named evt_tri_fun.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/exclusion_constraint_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/exclusion_constraint_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..a38a4271098a3b3a7df7d75fd733b6e6e0ae4a2b --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/exclusion_constraint_dialog.html @@ -0,0 +1,229 @@ + + + + + + + + + + Exclusion Constraint Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Exclusion Constraint Dialog

+

Use the Exclusion constraint dialog to define or modify the behavior of an +exclusion constraint. An exclusion constraint guarantees that if any two rows +are compared on the specified column or expression (using the specified +operator), at least one of the operator comparisons will return false or null.

+

The Exclusion constraint dialog organizes the development of an exclusion +constraint through the following dialog tabs: General, Definition, and +Columns. The SQL tab displays the SQL code generated by dialog selections.

+Exclusion constraint dialog general tab +

Use the fields in the General tab to identify the exclusion constraint:

+
    +
  • Use the Name field to provide a descriptive name for the exclusion +constraint. The name will be displayed in the pgAdmin tree control.

  • +
+

Click the Definition tab to continue.

+Exclusion constraint dialog definition tab +

Use the fields in the Definition tab to define the exclusion constraint:

+
    +
  • Use the drop-down listbox next to Tablespace to select the tablespace in +which the index associated with the exclude constraint will reside.

  • +
  • Use the drop-down listbox next to Access method to specify the type of +index that will be used when implementing the exclusion constraint:

    +
    +
      +
    • Select gist to specify a GiST index.

    • +
    • Select spgist to specify a space-partitioned GiST index.

    • +
    • Select btree to specify a B-tree index.

    • +
    • Select hash to specify a hash index.

    • +
    +
    +
  • +
  • Use the Fill Factor field to specify a fill factor for the table and +associated index. The fill factor is a percentage between 10 and 100. 100 +(complete packing) is the default.

  • +
  • Move the Deferrable? switch to the Yes position to specify that the +timing of the constraint is deferrable, and can be postponed until the end of +the statement. The default is No.

  • +
  • If enabled, move the Deferred? switch to the Yes position to specify the +timing of the constraint is deferred to the end of the statement. The default +is No.

  • +
  • Use the Constraint field to provide a condition that a row must satisfy to +be included in the table.

  • +
+

Click the Columns tab to continue.

+Exclusion constraint dialog columns tab +

Use the fields in the Columns tab to specify the column(s) or expression(s) +to which the constraint applies. Use the Is expression ? switch to enable +expression text input. Use the drop-down listbox next to Column +to select a column. Once the Column is selected or the Expression is +entered then click the Add icon (+) to provide details of the action on the +column/expression:

+
    +
  • The Col/Exp field is populated with the selection made in the Column +drop-down listbox or the Expression entered.

  • +
  • If applicable, use the drop-down listbox in the Operator class to specify +the operator class that will be used by the index for the column.

  • +
  • Move the DESC switch to DESC to specify a descending sort order. The +default is ASC which specifies an ascending sort order.

  • +
  • Use the NULLs order column to specify the placement of NULL values (when +sorted). Specify FIRST or LAST.

  • +
  • Use the drop-down list next to Operator to specify a comparison or +conditional operator.

  • +
+

Use Include columns field to specify columns for INCLUDE clause of the +constraint. This option is available in Postgres 11 and later.

+

Click the SQL tab to continue.

+

Your entries in the Exclusion Constraint dialog generate a SQL command (see +an example below). Use the SQL tab for review; revisit or switch tabs to make +any changes to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Exclusion Constraint dialog:

+Exclusion constraint dialog sql tab +

The example shown demonstrates creating an exclusion constraint named +ex_dept_no. The constraint uses a btree index.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/extension_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/extension_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..1069d51e4431d4cc0cc2acaa7ab99d77ed8209ba --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/extension_dialog.html @@ -0,0 +1,209 @@ + + + + + + + + + + Extension Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Extension Dialog

+

Use the Extension dialog to install a new extension into the current database. +An extension is a collection of SQL objects that add targeted functionality to +your Postgres installation. The Extension dialog adds the functionality of +an extension to the current database only; you must register the extension in +each database that use the extension. Before you load an extension into a +database, you should confirm that any pre-requisite files are installed.

+

The Extension dialog allows you to implement options of the CREATE EXTENSION +command through the following dialog tabs: General and Definition. The SQL +tab displays the SQL code generated by dialog selections.

+Extension dialog general tab +

Use the fields in the General tab to identify an extension:

+
    +
  • Use the drop-down listbox in the Name field to select the extension. Each +extension must have a unique name.

  • +
  • Move the switch next to Cascade? towards right position to automatically +install any extensions that this extension depends on that are not already +installed.

  • +
  • Store notes about the extension in the Comment field.

  • +
+

Click the Definition tab to continue.

+Extension dialog definition tab +

Use the Definition tab to select the Schema and Version:

+
    +
  • Use the drop-down listbox next to Schema to select the name of the schema +in which to install the extension’s objects.

  • +
  • Use the drop-down listbox next to Version to select the version of the +extension to install.

  • +
+

Click the SQL tab to continue.

+

Your entries in the Extension dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Extension dialog:

+Extension dialog sql tab +

The command creates the adminpack extension in the public schema. It is +version 2.0 of adminpack.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/external_database.html b/pgsql/pgAdmin 4/docs/en_US/html/external_database.html new file mode 100644 index 0000000000000000000000000000000000000000..13850be8787fd6abba49a6901bc4a934384baa09 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/external_database.html @@ -0,0 +1,183 @@ + + + + + + + + + + External database for pgAdmin user settings — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

External database for pgAdmin user settings

+

The user settings used by pgAdmin are stored in a SQLite database. In this +database, many settings are stored, such as preferences, user accounts, +auto-discovered servers, and many more.

+

As SQLite is a file-based database and it can be anywhere in the file system, +so it is not designed to take care of failures (no HA support). Furthermore, +it isn’t designed to handle multiple connections concurrently reading/writing +data to it. Example: In environments such as Kubernetes it may be useful to +use an alternate backend to avoid using SQLite on non-ephemeral storage and to +allow HA of the settings database.

+

In order to prevent this, pgAdmin now supports storing user settings in an +external database using the new ‘CONFIG_DATABASE_URI’ parameter in the +config.py file.

+
+

Use SQLite Database

+

In order to use SQLite Database, make sure CONFIG_DATABASE_URI parameter is +set to an empty string like ‘’. By default it is set to an empty string in the +config.py so if you would like to use SQLite database then no need to change +anything.

+
+
+

Use External Database

+

In order to use an external database, make sure CONFIG_DATABASE_URI parameter +is set like “dialect+driver://username:password@host:port/database”.

+

Note It is recommended to create the database in advance.

+
+
+

Use PostgreSQL Database

+

Following are the formats to use PostgreSQL as an external database.

+

Basic syntax:

+
postgresql://username:password@host:port/database
+
+
+

Using specific schema (It is recommended to create the schema in advance):

+
postgresql://username:password@host:port/database?options=-csearch_path=<schema name>
+
+
+

Using default pgpass path for the service account:

+
postgresql://username@host:port?options=-csearch_path=<schema name>
+
+
+

Specifying pgpass file path:

+
postgresql://username@host:port?passfile=<path of the pgpass file>&options=-csearch_path=<schema name>
+
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/foreign_data_wrapper_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/foreign_data_wrapper_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..1b34c2ae8cfa446271aa4b981da2308aeab6c0fe --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/foreign_data_wrapper_dialog.html @@ -0,0 +1,240 @@ + + + + + + + + + + Foreign Data Wrapper Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Foreign Data Wrapper Dialog

+

Use the Foreign Data Wrapper dialog to create or modify a foreign data +wrapper. A foreign data wrapper is an adapter between a Postgres database and +data stored on another data source.

+

You must be a superuser to create a foreign data wrapper.

+

The Foreign Data Wrapper dialog organizes the development of a foreign data +wrapper through the following dialog tabs: General, Definition, Options, +and Security. The SQL tab displays the SQL code generated by dialog +selections.

+Foreign data wrapper dialog general tab +

Use the fields in the General tab to identify the foreign data wrapper:

+
    +
  • Use the Name field to add a descriptive name for the foreign data wrapper. +A foreign data wrapper name must be unique within the database. The name will +be displayed in the pgAdmin tree control.

  • +
  • Use the drop-down listbox next to Owner to select the name of the role that +will own the foreign data wrapper.

  • +
  • Store notes about the foreign data wrapper in the Comment field.

  • +
+

Click the Definition tab to continue.

+Foreign data wrapper dialog definition tab +

Use the fields in the Definition tab to set parameters:

+
    +
  • Select the name of the handler function from the drop-down listbox in the +Handler field. This is the name of an existing function that will be called +to retrieve the execution functions for foreign tables.

  • +
  • Select the name of the validator function from the drop-down listbox in the +Validator field. This is the name of an existing function that will be +called to check the generic options given to the foreign data wrapper, as +well as options for foreign servers, user mappings and foreign tables using +the foreign data wrapper.

  • +
+

Click the Options tab to continue.

+Foreign data wrapper dialog options tab +

Use the fields in the Options tab to specify options:

+
    +
  • Click the Add icon (+) button to add an option/value pair for the +foreign data wrapper. Supported option/value pairs will be specific to the +selected foreign data wrapper.

  • +
  • Specify the option name in the Option field and provide a corresponding +value in the Value field.

  • +
+

Click the Add icon (+) to specify each additional pair; to discard an option, +click the trash icon to the left of the row and confirm deletion in the Delete +Row popup.

+

Click the Security tab to continue.

+Foreign data wrapper dialog security tab +

Use the Security tab to assign security privileges. Click the Add icon (+) +to assign a set of privileges.

+
    +
  • Select the name of the role from the drop-down listbox in the Grantee field.

  • +
  • Click inside the Privileges field. Check the boxes to the left of one or +more privileges to grant the selected privileges to the specified user.

  • +
  • The current user, who is the default grantor for granting the privilege, is displayed in the Grantor field.

  • +
+

Click add to assign additional privileges; to discard a privilege, click the +trash icon to the left of the row and confirm deletion in the Delete Row +popup.

+

Click the SQL tab to continue.

+

Your entries in the Foreign Data Wrapper dialog generate a SQL command (see an +example below). Use the SQL tab for review; revisit or switch tabs to make any +changes to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Foreign Data Wrapper dialog:

+Foreign data wrapper dialog sql tab +

The example creates a foreign data wrapper named lib_qp_debug that uses +pre-existing validator and handler functions, dblink_fdw_validator and +libpg_fdw_handler. Selections on the Options tab set debug equal to +true. The foreign data wrapper is owned by postgres.

+
    +
  • Click the Help button (?) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/foreign_key_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/foreign_key_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..d39daf69e7b5ac1edc9e17892c0f2d4f6b15d00c --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/foreign_key_dialog.html @@ -0,0 +1,265 @@ + + + + + + + + + + Foreign key Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Foreign key Dialog

+

Use the Foreign key dialog to specify the behavior of a foreign key +constraint. A foreign key constraint maintains referential integrity between +two tables. A foreign key constraint cannot be defined between a temporary +table and a permanent table.

+

The Foreign key dialog organizes the development of a foreign key constraint +through the following dialog tabs: General, Definition, Columns, and +Action. The SQL tab displays the SQL code generated by dialog selections.

+Foreign key dialog general tab +

Use the fields in the General tab to identify the foreign key constraint:

+
    +
  • Use the Name field to add a descriptive name for the foreign key. The name +will be displayed in the pgAdmin tree control.

  • +
  • Store notes about the foreign key constraint in the Comment field.

  • +
+

Click the Definition tab to continue.

+Foreign key dialog definition tab +

Use the fields in the Definition tab to define the foreign key constraint:

+
    +
  • Move the Deferrable? switch to the Yes position to specify the timing of +the constraint is deferrable and can be postponed until the end of the +statement. The default is No.

  • +
  • If enabled, move the Deferred? switch to the Yes position to specify the +timing of the constraint is deferred to the end of the statement. The default +is No.

  • +
  • Move the Match type switch specify the type of matching that is enforced by +the constraint:

    +
    +
      +
    • Select Full to indicate that all columns of a multicolumn foreign key +must be null if any column is null; if all columns are null, the row is +not required to have a match in the referenced table.

    • +
    • Select Simple to specify that a single foreign key column may be null; +if any column is null, the row is not required to have a match in the +referenced table.

    • +
    +
    +
  • +
  • Move the Validated switch to the Yes position to instruct the server to +validate the existing table content (against a foreign key or check +constraint) when you save modifications to this dialog.

  • +
  • Move the Auto FK Index switch to the No position to disable the automatic +index feature.

  • +
  • The field next to Covering Index generates the name of an index if the Auto +FK Index switch is in the Yes position; or, this field is disabled.

  • +
+

Click the Columns tab to continue.

+Foreign key dialog columns tab +

Use the fields in the Columns tab to specify one or more reference column(s). +A Foreign Key constraint requires that one or more columns of a table must only +contain values that match values in the referenced column(s) of a row of a +referenced table:

+
    +
  • Use the drop-down listbox next to Local column to specify the column in the +current table that will be compared to the foreign table.

  • +
  • Use the drop-down listbox next to References to specify the name of the +table in which the comparison column(s) resides.

  • +
  • Use the drop-down listbox next to Referencing to specify a column in the +foreign table.

  • +
+

Click the Add icon (+) to add a column to the list; repeat the steps above and +click the Add icon (+) to add additional columns. To discard an entry, click +the trash icon to the left of the entry and confirm deletion in the Delete Row +popup.

+

Click the Action tab to continue.

+Foreign key dialog action tab +

Use the drop-down listboxes on the Action tab to specify behavior related to +the foreign key constraint that will be performed when data within the table is +updated or deleted:

+
    +
  • Use the drop-down listbox next to On update to select an action that will be +performed when data in the table is updated.

  • +
  • Use the drop-down listbox next to On delete to select an action that will be +performed when data in the table is deleted.

  • +
+

The supported actions are:

+ + + + + + + + + + + + + + + + + + +

NO ACTION

Produce an error indicating that the deletion or update will create a foreign key constraint violation. +If the constraint is deferred, this error will be produced at constraint check time if any referencing +rows still exist. This is the default.

RESTRICT

Throw an error indicating that the deletion or update would create a foreign key constraint violation. +This is the same as NO ACTION except that the check is not deferrable.

CASCADE

Delete any rows referencing the deleted row, or update the values of the referencing column(s) to the new +values of the referenced columns, respectively.

SET NULL

Set the referencing column(s) to null.

SET DEFAULT

Set the referencing column(s) to their default values. There must be a row in the referenced table +that matches the default values (if they are not null), or the operation will fail.

+

Click the SQL tab to continue.

+

Your entries in the Foreign key dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Foreign key dialog:

+Foreign key dialog sql tab +

The example shown demonstrates creating a foreign key constraint named +jobhist_ref_dept_fk that matches values in the jobhist table dept_no +column with those of the dept table deptno column.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/foreign_server_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/foreign_server_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..99022fd50c3434c03b5a7f7171ad63feae05e9c0 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/foreign_server_dialog.html @@ -0,0 +1,230 @@ + + + + + + + + + + Foreign Server Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Foreign Server Dialog

+

Use the Foreign Server dialog to create a foreign server. A foreign server +typically encapsulates connection information that a foreign-data wrapper uses +to access an external data resource. Each foreign data wrapper may connect to a +different foreign server; in the pgAdmin tree control, expand the node of the +applicable foreign data wrapper to launch the Foreign Server dialog.

+

The Foreign Server dialog organizes the development of a foreign server +through the following dialog tabs: General, Definition, Options, and +Security. The SQL tab displays the SQL code generated by dialog selections.

+Foreign server dialog general tab +

Use the fields in the General tab to identify the foreign server:

+
    +
  • Use the Name field to add a descriptive name for the foreign server. The +name will be displayed in the pgAdmin tree control. It must be unique within +the database.

  • +
  • Use the drop-down listbox next to Owner to select a role.

  • +
  • Store notes about the foreign server in the Comment field.

  • +
+

Click the Definition tab to continue.

+Foreign server dialog definition tab +

Use the fields in the Definition tab to set parameters:

+
    +
  • Use the Type field to specify a server type.

  • +
  • Use the Version field to specify a server version.

  • +
+

Click the Options tab to continue.

+Foreign server dialog options tab +

Use the fields in the Options tab to specify options. Click the Add button +to create an option clause for the foreign server.

+
    +
  • Specify the option name in the Option field.

  • +
  • Provide a corresponding value in the Value field.

  • +
+

Click Add to create each additional clause; to discard an option, click the +trash icon to the left of the row and confirm deletion in the Delete Row +popup.

+

Click the Security tab to continue.

+Foreign server dialog security tab +

Use the Security tab to assign security privileges to the foreign server. +Click Add before you assign a set of privileges.

+
    +
  • Select the name of the role from the drop-down listbox in the Grantee field.

  • +
  • Click inside the Privileges field. Check the boxes to the left of one or +more privileges to grant the selected privileges to the specified user.

  • +
  • The current user, who is the default grantor for granting the privilege, is displayed in the Grantor field.

  • +
+

Click Add to assign a new set of privileges; to discard a privilege, click the +trash icon to the left of the row and confirm deletion in the Delete Row +dialog.

+

Click the SQL tab to continue.

+

Your entries in the Foreign Server dialog generate a SQL command (see an +example below). Use the SQL tab for review; revisit or switch tabs to make +any changes to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Foreign Server dialog:

+Foreign server dialog sql tab +

The example shown demonstrates creating a foreign server for the foreign data +wrapper hdfs_fdw. It has the name hdfs_server; its type is hiveserver2. +Options for the foreign server include a host and a port.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/foreign_table_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/foreign_table_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..6c525afbfffc9a39cb0b21aa36fba17264c6185a --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/foreign_table_dialog.html @@ -0,0 +1,286 @@ + + + + + + + + + + Foreign Table Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Foreign Table Dialog

+

Use the Foreign Table dialog to define a foreign table in the current +database. Foreign tables define the structure of an external data source that +resides on a foreign server.

+

The Foreign Table dialog organizes the development of a foreign table through +the following dialog tabs: General, Definition, Columns, Constraints, +Options, and Security. The SQL tab displays the SQL code generated by +dialog selections.

+Foreign table dialog general tab +

Use the fields in the General tab to identify the foreign table:

+
    +
  • Use the Name field to add a descriptive name for the foreign table. The name +of the foreign table must be distinct from the name of any other foreign +table, table, sequence, index, view, existing data type, or materialized view +in the same schema. The name will be displayed in the pgAdmin tree control.

  • +
  • Use the drop-down listbox next to Owner to select the name of the role that +will own the foreign table.

  • +
  • Select the name of the schema in which the foreign table will reside from the +drop-down listbox in the Schema field.

  • +
  • Store notes about the foreign table in the Comment field.

  • +
+

Click the Definition tab to continue.

+Foreign table dialog definition tab +

Use the fields in the Definition tab to define the external data source:

+
    +
  • Use the drop-down listbox next to Foreign server to select a foreign server. +This list is populated with servers defined through the Foreign Server +dialog.

  • +
  • Use the drop-down listbox next to Inherits to specify a parent table. The +foreign table will inherit all of its columns. This field is optional.

  • +
+

Click the Columns tab to continue.

+Foreign table dialog columns tab +

Use the fields in the Columns tab to add columns and their attributes to +the table. Click the Add icon (+) to define a column:

+
    +
  • Use the Name field to add a descriptive name for the column.

  • +
  • Use the drop-down listbox in the Data Type field to select a data type for +the column. This can include array specifiers. For more information on which +data types are supported by PostgreSQL, refer to Chapter 8 of the core +documentation.

  • +
+

Click the Add icon (+) to specify each additional column; to discard a column, +click the trash icon to the left of the row and confirm deletion in the Delete +Row popup.

+

Click the Constraints tab to continue.

+Foreign table dialog constraints tab +

Use the fields in the Constraints tab to apply a table constraint to the +foreign table. Click the Add icon (+) to define a constraint:

+
    +
  • Use the Name field to add a descriptive name for the constraint. If the +constraint is violated, the constraint name is present in error messages, so +constraint names like col must be positive can be used to communicate +helpful information.

  • +
  • Use the Check field to write a check expression producing a Boolean result. +Each row in the foreign table is expected to satisfy the check expression.

  • +
  • Check the No Inherit checkbox to specify that the constraint will not +propagate to child tables.

  • +
  • Uncheck the Validate checkbox to disable validation. The database will not +assume that the constraint holds for all rows in the table.

  • +
+

Click the Add icon (+) to specify each additional constraint; to discard a +constraint, click the trash icon to the left of the row and confirm deletion in +he Delete Row popup.

+

Click the Options tab to continue.

+Foreign table dialog options tab +

Use the fields in the Options tab to specify options to be associated with +the new foreign table or one of its columns; the accepted option names and +values are specific to the foreign data wrapper associated with the foreign +server. Click the Add icon (+) to add an option/value pair.

+
    +
  • Specify the option name in the Option field. Duplicate option names are not +allowed.

  • +
  • Provide a corresponding value in the Value field.

  • +
+

Click the Add icon (+) to specify each additional option/value pair; to +discard an option, click the trash icon to the left of the row and confirm +deletion in the Delete Row popup.

+

Click the Security tab to continue.

+Foreign table dialog security tab +

Use the Security tab to assign privileges and define security labels.

+

Use the Privileges panel to assign privileges to a role. Click the Add icon +(+) to set privileges for database objects:

+
    +
  • Select the name of the role to which privileges will be assigned from the +drop-down listbox in the Grantee field.

  • +
  • Click inside the Privileges field. Check the boxes to the left of one or +more privileges to grant the selected privilege to the specified user.

  • +
  • The current user, who is the default grantor for granting the privilege, is displayed in the Grantor field.

  • +
+

Click the Add icon (+) to assign additional privileges; to discard a +privilege, click the trash icon to the left of the row and confirm deletion in +the Delete Row popup.

+

Use the Security Labels panel to define security labels applied to the +function. Click the Add icon (+) to add each security label selection:

+
    +
  • Specify a security label provider in the Provider field. The named provider +must be loaded and must consent to the proposed labeling operation.

  • +
  • Specify a a security label in the Security Label field. The meaning of a +given label is at the discretion of the label provider. PostgreSQL places no +restrictions on whether or how a label provider must interpret security +labels; it merely provides a mechanism for storing them.

  • +
+

Click the Add icon (+) to assign additional security labels; to discard a +security label, click the trash icon to the left of the row and confirm deletion +in the Delete Row popup.

+

Click the SQL tab to continue.

+

Your entries in the Foreign Table dialog generate a SQL command (see an +example below). Use the SQL tab for review; revisit or switch tabs to make +any changes to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Foreign Table dialog:

+Foreign table dialog sql tab +

The example shown demonstrates creating a foreign table weblogs with multiple +columns.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/fts_configuration_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/fts_configuration_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..2d19f00bfb40bc9d18ff30ece9b7e292e1609cc2 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/fts_configuration_dialog.html @@ -0,0 +1,218 @@ + + + + + + + + + + FTS Configuration Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

FTS Configuration Dialog

+

Use the FTS Configuration dialog to configure a full text search. A text +search configuration specifies a text search parser that can divide a string +into tokens, along with dictionaries that can identify searchable tokens.

+

The FTS Configuration dialog organizes the development of a FTS configuration +through the following dialog tabs: “General, Definition, and Tokens. The +SQL tab displays the SQL code generated by dialog selections.

+

Click the General tab to begin.

+FTS configuration dialog general tab +

Use the fields in the General tab to identify a FTS configuration:

+
    +
  • Use the Name field to add a descriptive name for the FTS configuration. The +name will be displayed in the pgAdmin tree control.

  • +
  • Use the drop-down listbox next to Owner to specify the role that will own +the configuration.

  • +
  • Select the name of the schema in which the FTS configuration will reside from +the drop-down listbox in the Schema field.

  • +
  • Store notes about the FTS configuration in the Comment field.

  • +
+

Click the Definition tab to continue.

+FTS configuration dialog definition tab +

Use the fields in the Definition tab to define parameters:

+
    +
  • Select the name of the text search parser from the drop-down listbox in the +Parser field.

  • +
  • Select a language from the drop-down listbox in the Copy Config field.

  • +
+

Click the Tokens tab to continue.

+FTS configuration dialog tokens tab +

Use the fields in the Tokens tab to add a token:

+
    +
  • Use the Tokens field to specify the name of a token.

  • +
  • Click the Add button to create a token.

  • +
  • Use the Dictionaries field to specify a dictionary.

  • +
+

Repeat these steps to add additional tokens; to discard a token, click the +trash icon to the left of the row and confirm deletion in the Delete Row +popup.

+

Click the SQL tab to continue.

+

Your entries in the FTS Configuration dialog generate a SQL command (see an +example below). Use the SQL tab for review; revisit or switch tabs to make +any changes to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the FTS Configuration dialog:

+FTS configuration dialog sql tab +

The example shown demonstrates creating a FTS configuration named +english_phrases. It uses the default parser.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/fts_dictionary_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/fts_dictionary_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..e9ad945c46b81eb64fbcf7e6195e977f2b303c6c --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/fts_dictionary_dialog.html @@ -0,0 +1,250 @@ + + + + + + + + + + FTS Dictionary Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

FTS Dictionary Dialog

+

Use the FTS Dictionary dialog to create a full text search dictionary. You +can use a predefined templates or create a new dictionary with custom +parameters.

+

The FTS Dictionary dialog organizes the development of a FTS dictionary +through the following dialog tabs: General, Definition, and Options. The +SQL tab displays the SQL code generated by dialog selections.

+FTS dictionary dialog general tab +

Use the fields in the General tab to identify the dictionary:

+
    +
  • Use the Name field to add a descriptive name for the dictionary. The name +will be displayed in the pgAdmin tree control.

  • +
  • Use the drop-down listbox next to Owner to select the role that will own the +FTS Dictionary.

  • +
  • Select the name of the schema in which the dictionary will reside from the +drop-down listbox in the Schema field.

  • +
  • Store notes about the dictionary in the Comment field.

  • +
+

Click the Definition tab to continue.

+FTS dictionary dialog definition tab +

Use the field in the Definition tab to choose a template from the drop-down +listbox:

+
    +
  • Select ispell to select the Ispell template. The Ispell dictionary template +supports morphological dictionaries, which can normalize many different +linguistic forms of a word into the same lexeme. For example, an English +Ispell dictionary can match all declensions and conjugations of the search +term bank, e.g., banking, banked, banks, banks’, and bank’s. Ispell +dictionaries usually recognize a limited set of words, so they should be +followed by another broader dictionary; for example, a Snowball dictionary, +which recognizes everything.

  • +
  • Select simple to select the simple template. The simple dictionary template +operates by converting the input token to lower case and checking it against +a file of stop words. If it is found in the file then an empty array is +returned, causing the token to be discarded. If not, the lower-cased form of +the word is returned as the normalized lexeme. Alternatively, the dictionary +can be configured to report non-stop-words as unrecognized, allowing them to +be passed on to the next dictionary in the list.

  • +
  • Select snowball to select the Snowball template. The Snowball dictionary +template is based on a project by Martin Porter, inventor of the popular +Porter’s stemming algorithm for the English language. Snowball now provides +stemming algorithms for many languages (see the Snowball site for more +information). Each algorithm understands how to reduce common variant forms of +words to a base, or stem, spelling within its language. A Snowball dictionary +recognizes everything, whether or not it is able to simplify the word, so it +should be placed at the end of the dictionary list. It is useless to have it +before any other dictionary because a token will never pass through it to the +next dictionary.

  • +
  • Select synonym to select the synonym template. This dictionary template is +used to create dictionaries that replace a word with a synonym. Phrases are not +supported (use the thesaurus template (Section 12.6.4) for that). A synonym +dictionary can be used to overcome linguistic problems, for example, to prevent +an English stemmer dictionary from reducing the word Paris to pari.

  • +
  • Select thesaurus to select the thesaurus template. A thesaurus dictionary +replaces all non-preferred terms by one preferred term and, optionally, +preserves the original terms for indexing as well. PostgreSQL’s current +implementation of the thesaurus dictionary is an extension of the synonym +dictionary with added phrase support.

  • +
+

Click the Options tab to continue.

+FTS dictionary dialog options tab +

Use the fields in the Options tab to provide template-specific options. Click +the Add icon (+) to add an option clause:

+
    +
  • Specify the name of an option in the Option field

  • +
  • Provide a value for the option in the Value field.

  • +
+

Click the Add icon (+) to specify each additional option/value pair; to +discard an option, click the trash icon to the left of the row and confirm +deletion in the Delete Row popup.

+

Click the SQL tab to continue.

+

Your entries in the FTS Dictionary dialog generate a generate a SQL command. +Use the SQL tab for review; revisit or switch tabs to make any changes to the +SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the FTS Dictionary dialog:

+FTS dictionary dialog sql tab +

The example shown demonstrates creating a custom dictionary named +more_stopwords which is based on the simple template and is configured to use standard English.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/fts_parser_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/fts_parser_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..f566266b6dfa08fadab042cb537aba57a7cc7e09 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/fts_parser_dialog.html @@ -0,0 +1,197 @@ + + + + + + + + + + FTS Parser Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

FTS Parser Dialog

+

Use the FTS Parser dialog to create a new text search parser. A text search +parser defines a method for splitting a text string into tokens and assigning +types (categories) to the tokens.

+

The FTS Parser dialog organizes the development of a text search parser +through the following dialog tabs: General, and Definition. The SQL tab +displays the SQL code generated by dialog selections.

+FTS parser dialog general tab +

Use the fields in the General tab to identify a text search parser:

+
    +
  • Use the Name field to add a descriptive name for the parser. The name will +be displayed in the pgAdmin tree control.

  • +
  • Select the name of the schema in which the parser will reside from the +drop-down listbox in the Schema field.

  • +
  • Store notes about the domain in the Comment field.

  • +
+

Click the Definition tab to continue.

+FTS parser dialog definition tab +

Use the fields in the Definition tab to define parameters:

+
    +
  • Use the drop-down listbox next to Start function to select the name of the +function that will initialize the parser.

  • +
  • Use the drop-down listbox next to Get next token function to select the +name of the function that will return the next token.

  • +
  • Use the drop-down listbox next to End function to select the name of the +function that is called when the parser is finished.

  • +
  • Use the drop-down listbox next to Lextypes function to select the name of +the lextypes function for the parser. The lextypes function returns an array +that contains the id, alias, and a description of the tokens used by the +parser.

  • +
  • Use the drop-down listbox next to Headline function to select the name of +the headline function for the parser. The headline function returns an excerpt +from the document in which the terms of the query are highlighted.

  • +
+

Click the SQL tab to continue.

+FTS parser dialog sql tab +

Your entries in the FTS Parser dialog generate a generate a SQL command. Use +the SQL tab for review; revisit or switch tabs to make any changes to the SQL +command.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/fts_template_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/fts_template_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..b6ae8c21fecc9544ae0086fbe846e0dab364187e --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/fts_template_dialog.html @@ -0,0 +1,204 @@ + + + + + + + + + + FTS Template Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

FTS Template Dialog

+

Use the FTS Template dialog to create a new text search template. A text +search template defines the functions that implement text search dictionaries.

+

The FTS Template dialog organizes the development of a text search Template +through the following dialog tabs: General, and Definition. The SQL tab +displays the SQL code generated by dialog selections.

+FTS template dialog general tab +

Use the fields in the General tab to identify a template:

+
    +
  • Use the Name field to add a descriptive name for the template. The name will +be displayed in the pgAdmin tree control.

  • +
  • Select the name of the schema in which the template will reside from the +drop-down listbox in the Schema field.

  • +
  • Store notes about the template in the Comment field.

  • +
+

Click the Definition tab to continue.

+FTS template dialog definition tab +

Use the fields in the Definition tab to define function parameters:

+
    +
  • Use the drop-down listbox next to Init function to select the name of the +init function for the template. The init function is optional.

  • +
  • Use the drop-down listbox next to Lexize function to select the name of the +lexize function for the template. The lexize function is required.

  • +
+

Click the SQL tab to continue.

+

Your entries in the FTS Template dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the FTS Template dialog:

+FTS template dialog sql tab +

The example shown demonstrates creating a fts template named eng.template that +uses the ispell dictionary.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/function_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/function_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..ef2dbd2b4dd1467644b221983b06bcf0bfa09de7 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/function_dialog.html @@ -0,0 +1,317 @@ + + + + + + + + + + Function Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Function Dialog

+

Use the Function dialog to define a function. If you drop and then recreate +a function, the new function is not the same entity as the old; you must drop +existing rules, views, triggers, etc. that refer to the old function.

+

The Function dialog organizes the development of a function through the +following dialog tabs: General, Definition, Code, Options, +Parameters, and Security. The SQL tab displays the SQL code generated by +dialog selections.

+Function dialog general tab +

Use the fields in the General tab to identify a function:

+
    +
  • Use the Name field to add a descriptive name for the function. The name will +be displayed in the pgAdmin tree control.

  • +
  • Use the drop-down listbox next to Owner to select the name of the role that +will own the function.

  • +
  • Use the drop-down listbox next to Schema to select the schema in which the +function will be created.

  • +
  • Store notes about the function in the Comment field.

  • +
+

Click the Definition tab to continue.

+Function dialog definition tab +

Use the fields in the Definition tab to define the function:

+
    +
  • Move the Custom return type? switch to provide a user defined return type.

  • +
  • Use the drop-down listbox next to Return type to select the data type +returned by the function, if any. If Custom return type? is enabled this field +will change to an input text field.

  • +
  • Use the drop-down listbox next to Language to select the implementation +language. The default is sql.

  • +
  • Use the fields in the Arguments to define an argument. Click the Add +icon (+) to set parameters and values for the argument:

    +
      +
    • Use the drop-down listbox in the Data type field to select a data type.

    • +
    • Use the drop-down listbox in the Mode field to select a mode. Select IN +for an input parameter; select OUT for an output parameter; select INOUT +for both an input and an output parameter; or, select VARIADIC to specify a +VARIADIC parameter.

    • +
    • Provide a name for the argument in the Argument Name field.

    • +
    • Specify a default value for the argument in the Default Value field.

    • +
    +
  • +
+

Click the Add icon (+) to define another argument; to discard an argument, +click the trash icon to the left of the row and confirm deletion in the Delete +Row popup.

+

Click the Code tab to continue.

+Function dialog code tab +
    +
  • Use the Code field to write the code that will execute when the function +is called.

  • +
+

Click the Options tab to continue.

+Function dialog options tab +

Use the fields in the Options tab to describe or modify the action of the +function:

+
    +
  • Use the drop-down listbox next to Volatility to select one of the following. +VOLATILE is the default value.

    +
    +
      +
    • VOLATILE indicates that the function value can change even within a +single table scan, so no optimizations can be made.

    • +
    • STABLE indicates that the function cannot modify the database, and that +within a single table scan it will consistently return the same result for +the same argument values.

    • +
    • IMMUTABLE indicates that the function cannot modify the database and +always returns the same result when given the same argument values.

    • +
    +
    +
  • +
  • Move the Returns a Set? switch to indicate if the function returns a set +that includes multiple rows. The default is No.

  • +
  • Move the Strict? switch to indicate if the function always returns NULL +whenever any of its arguments are NULL. If Yes, the function is not executed +when there are NULL arguments; instead a NULL result is assumed +automatically. The default is No.

  • +
  • Move the Security of definer? switch to specify that the function is to be +executed with the privileges of the user that created it. The default is No.

  • +
  • Move the Window? switch to indicate that the function is a window function +rather than a plain function. The default is No. This is currently only +useful for functions written in C. The WINDOW attribute cannot be changed when +replacing an existing function definition. For more information about the +CREATE FUNCTION command, see the PostgreSQL core documentation available at:

    +
    +
    +
  • +
  • Use the Estimated cost field to specify a positive number representing the +estimated execution cost for the function, in units of cpu_operator_cost. If +the function returns a set, this is the cost per returned row.

  • +
  • Use the Estimated rows field to specify a positive number giving the +estimated number of rows that the query planner should expect the function to +return. This is only allowed when the function is declared to return a set. +The default assumption is 1000 rows.

  • +
  • Move the Leak proof? switch to indicate whether the function has side +effects. The default is No. This option can only be set by the superuser.

  • +
  • Use the Support function field to specify a planner support function to +use for the function.

  • +
+

Click the Parameters tab to continue.

+Function dialog parameters tab +

Use the fields in the Parameters tab to specify settings that will be applied +when the function is invoked. Click the Add icon (+) to add a Name/Value +field in the table.

+
    +
  • Use the drop-down listbox in the Name column in the Parameters panel to +select a parameter.

  • +
  • Use the Value field to specify the value that will be associated with the +selected variable. This field is context-sensitive.

  • +
+

Click the Security tab to continue.

+Function dialog security tab +

Use the Security tab to assign privileges and define security labels.

+

Use the Privileges panel to assign usage privileges for the function to a +role.

+
    +
  • Select the name of the role from the drop-down listbox in the Grantee field.

  • +
  • Click inside the Privileges field. Check the boxes to the left of one or +more privileges to grant the selected privilege to the specified user.

  • +
  • The current user, who is the default grantor for granting the privilege, is displayed in the Grantor field.

  • +
+

Click the Add icon (+) to assign additional privileges; to discard a +privilege, click the trash icon to the left of the row and confirm deletion in +the Delete Row popup.

+

Use the Security Labels panel to define security labels applied to the +function. Click the Add icon (+) to add each security label selection:

+
    +
  • Specify a security label provider in the Provider field. The named provider +must be loaded and must consent to the proposed labeling operation.

  • +
  • Specify a a security label in the Security Label field. The meaning of a +given label is at the discretion of the label provider. PostgreSQL places no +restrictions on whether or how a label provider must interpret security +labels; it merely provides a mechanism for storing them.

  • +
+

Click the Add icon (+) to assign additional security labels; to discard a +security label, click the trash icon to the left of the row and confirm deletion +in the Delete Row popup.

+

Click the SQL tab to continue.

+

Your entries in the Function dialog generate a generate a SQL command (see an +example below). Use the SQL tab for review; revisit or switch tabs to make any +changes to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by selections made in +the Function dialog:

+Function dialog sql tab +

The example demonstrates creating an plpgsql function named hire_salesmen. The +function have three columns (p_ename, p_sal and p_comm).

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/genindex.html b/pgsql/pgAdmin 4/docs/en_US/html/genindex.html new file mode 100644 index 0000000000000000000000000000000000000000..0f9389871d3f3852ae973d1cb49c97d6499d94d4 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/genindex.html @@ -0,0 +1,513 @@ + + + + + + + + + Index — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + +
+
+
+
+ + +

Index

+ +
+ A + | B + | C + | D + | E + | F + | G + | I + | K + | L + | M + | P + | Q + | R + | S + | T + | U + | V + +
+

A

+ + + +
+ +

B

+ + + +
+ +

C

+ + + +
+ +

D

+ + + +
+ +

E

+ + + +
+ +

F

+ + + +
+ +

G

+ + + +
+ +

I

+ + + +
+ +

K

+ + +
+ +

L

+ + + +
+ +

M

+ + + +
+ +

P

+ + + +
+ +

Q

+ + + +
+ +

R

+ + + +
+ +

S

+ + + +
+ +

T

+ + + +
+ +

U

+ + + +
+ +

V

+ + + +
+ + + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/getting_started.html b/pgsql/pgAdmin 4/docs/en_US/html/getting_started.html new file mode 100644 index 0000000000000000000000000000000000000000..2ce3c97d29d358b0cc306c5c90c0ac01495b8f95 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/getting_started.html @@ -0,0 +1,283 @@ + + + + + + + + + + Getting Started — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Getting Started

+

Pre-compiled and configured installation packages for pgAdmin 4 are available +for a number of desktop environments; we recommend using an installer +whenever possible.

+

In a Server Deployment, the pgAdmin application is deployed behind a webserver +or with the WSGI interface. +If you install pgAdmin in server mode, you will be prompted to provide a role +name and pgAdmin password when you initially connect to pgAdmin. The first +role registered with pgAdmin will be an administrative user; the +administrative role can use the pgAdmin User Management dialog to create +and manage additional pgAdmin user accounts. When a user authenticates +with pgAdmin, the pgAdmin tree control displays the server definitions +associated with that login role.

+

In a Desktop Deployment, the pgAdmin application is configured to use the +desktop runtime environment to host the program on a supported platform. +Typically, users will install a pre-built package to run pgAdmin in desktop +mode, but a manual desktop deployment can be installed and though it is more +difficult to setup, it may be useful for developers interested in understanding +how pgAdmin works.

+

It is also possible to use a Container Deployment of pgAdmin, in which Server +Mode is pre-configured for security.

+ +
+

Note

+

Pre-compiled and configured installation packages are available for +a number of platforms. These packages should be used by end-users whereever +possible - the following information is useful for the maintainers of those +packages and users interested in understanding how pgAdmin works.

+
+

The pgAdmin 4 client features a highly-customizable display that features +drag-and-drop panels that you can arrange to make the best use of your desktop +environment.

+

The tree control provides an elegant overview of the managed servers, and the +objects that reside on each server. Right-click on a node within the tree control +to access context-sensitive menus that provide quick access to management tasks +for the selected object.

+

The tabbed browser provide quick access to statistical information about each +object in the tree control, and pgAdmin tools and utilities (such as the Query +tool and the debugger). pgAdmin opens additional feature tabs each time you +access the extended functionality offered by pgAdmin tools; you can open, close, +and re-arrange feature tabs as needed.

+

Use the Preferences dialog to customize the content and behaviour of the pgAdmin +display. To open the Preferences dialog, select Preferences from the File menu.

+

Help buttons in the lower-left corner of each dialog will open the online help +for the dialog. You can access additional Postgres help by navigating through +the Help menu, and selecting the name of the resource that you wish to open.

+

You can search for objects in the database using the Search objects

+ +

Before using pgAdmin to manage objects that reside on a server, you must define a +connection to the server; for more information please see Connecting to a Server +in the next section.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/grant_wizard.html b/pgsql/pgAdmin 4/docs/en_US/html/grant_wizard.html new file mode 100644 index 0000000000000000000000000000000000000000..ff9800e0331acd73bae2d98b788704044d527d4a --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/grant_wizard.html @@ -0,0 +1,210 @@ + + + + + + + + + + Grant Wizard — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Grant Wizard

+

The Grant Wizard tool is a graphical interface that allows you to manage the +privileges of one or more database objects in a point-and-click environment. A +search box, dropdown lists, and checkboxes facilitate quick selections of +database objects, roles and privileges.

+

The wizard organizes privilege management through a sequence of windows: +Object Selection, Privileges Selection and +Review Selection. The Review Selection window +displays the SQL code generated by wizard selections.

+

To launch the Grant Wizard tool, select a database object in the pgAdmin +tree control, then navigate through Tools on the menu bar to click on the +Grant Wizard option.

+Grant wizard step one page +

Use the fields in the Object Selection window to select the +object or objects on which you are modifying privileges. Use the Search by +object type or name field to locate a database object, or use the scrollbar +to scroll through the list of all accessible objects.

+
    +
  • Each row in the table lists object identifiers; check the checkbox in the left +column to include an object as a target of the Grant Wizard. The table +displays:

    +
    +
      +
    • The object type in the Object Type field

    • +
    • The schema in which the object resides in the Schema field

    • +
    • The object name in the Name field.

    • +
    +
    +
  • +
+

Click the Next button to continue, or the X button to close the wizard +without modifying privileges.

+Grant wizard step two page +

Use the fields in the Privileges Selection window to grant +privileges. If you grant a privilege WITH GRANT OPTION, the Grantee will have +the right to grant privileges on the object to others. If WITH GRANT OPTION is +subsequently revoked, any role who received access to that object from that +Grantee (directly or through a chain of grants) will lose thier privileges on +the object.

+
    +
  • Click the Add icon (+) to assign a set of privileges.

  • +
  • Select the name of the role from the drop-down listbox in the Grantee field.

  • +
  • Click inside the Privileges field. Check the boxes to the left of one or +more privileges to grant the selected privileges to the specified user. If +privileges have previously been granted on a database object, unchecking a +privilege for a group or user will result in revoking that privilege.

  • +
  • The current user, who is the default grantor for granting the privilege, is displayed in the Grantor field.

  • +
  • Click the Add icon (+) to assign a set of privileges to another role; to +discard a privilege, click the trash icon to the left of the row and confirm +deletion in the Delete Row dialog.

  • +
+

For more information about granting privileges on database objects, see the +PostgreSQL core documentation.

+

Click the Next button to continue, the Back button to select or deselect +additional database objects, or the X button to close the wizard without +modifying privileges.

+

Your entries in the Grant Wizard tool generate a SQL command; you can review +the command in the Review Selection window (see an +example below).

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Grant Wizard tool:

+Grant wizard step three page +
    +
  • Click the Back button to select or deselect additional database objects, +roles and privileges.

  • +
  • Click the Finish button to save selections and exit the wizard.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/import_export_data.html b/pgsql/pgAdmin 4/docs/en_US/html/import_export_data.html new file mode 100644 index 0000000000000000000000000000000000000000..0a7909ab22ca4d5cbba8f3d73b97ff92c028b1fd --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/import_export_data.html @@ -0,0 +1,206 @@ + + + + + + + + + + Import/Export Data Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Import/Export Data Dialog

+

Use the Import/Export data dialog to copy data from a table to a file, or copy +data from a file into a table.

+

The Import/Export data dialog organizes the import/export of data through the +General, Options and Columns tabs.

+Import Export data dialog general tab +

Use the fields in the General tab to specify import and export preferences:

+
    +
  • Move the Import/Export switch to the Import position to specify that the +server should import data to a table from a file. The default is Import.

  • +
  • Enter the name of the source or target file in the Filename field. +Optionally, select the Browse icon (ellipsis) to the right to navigate +into a directory and select a file.

  • +
  • Use the drop-down listbox in the Format field to specify the file type. +Select:

    +
      +
    • binary for a .bin file.

    • +
    • csv for a .csv file.

    • +
    • text for a .txt file.

    • +
    +
  • +
  • Use the drop-down listbox in the Encoding field to specify the type of +character encoding.

  • +
+Import Export data dialog options tab +
    +
  • Use the fields in the Options tab to specify additional information:

    +
    +
      +
    • Move the OID switch to the Yes position to include the OID column. +The OID is a system-assigned value that may not be modified. The default +is No.

    • +
    • Move the Header switch to the Yes position to include the table header +with the data rows. If you include the table header, the first row of the +file will contain the column names.

    • +
    • If you are exporting data, specify the delimiter that will separate the +columns within the target file in the Delimiter field. The separating +character can be a colon, semicolon, a vertical bar, or a tab.

    • +
    • Specify a quoting character used in the Quote field. Quoting can be +applied to string columns only (i.e. numeric columns will not be quoted) +or all columns regardless of data type. The character used for quoting can +be a single quote or a double quote.

    • +
    • Specify a character that should appear before a data character that matches +the QUOTE value in the Escape field.

    • +
    • Use the NULL Strings field to specify a string that will represent a null +value within the source or target file.

    • +
    +
    +
  • +
+

Click the Columns tab to continue.

+Import Export data dialog columns tab +

Use the fields in the Columns tab to select the columns that will be imported +or exported:

+
    +
  • Click inside the Columns to export/import field to deselect one or more +columns from the drop-down listbox. To delete a selection, click the x to +the left of the column name. Click an empty spot inside the field to access +the drop-down list.

  • +
  • If enabled, click inside the NOT NULL columns field to select one or more +columns that will not be checked for a NULL value. To delete a column, click +the x to the left of the column name.

  • +
+

After completing the Import/Export data dialog, click the OK button to +perform the import or export. pgAdmin will inform you when the background +process completes:

+Import Export data completion notification +

Use the Stop Process button to stop the Import/Export process.

+

Use the Click here for details link on the notification to open the Process +Watcher and review detailed information about the execution of the command +that performed the import or export:

+Import Export data process watcher +
+

Note

+

If you are running pgAdmin in Server Mode you can click on the sm_icon icon in the process watcher window to open the file location in the Storage Manager. You can use the Storage Manager to download the backup file on the client machine .

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/import_export_servers.html b/pgsql/pgAdmin 4/docs/en_US/html/import_export_servers.html new file mode 100644 index 0000000000000000000000000000000000000000..ea3eed19a72488ce366cd141668db78aa33a82f1 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/import_export_servers.html @@ -0,0 +1,306 @@ + + + + + + + + + + Import/Export Servers — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Import/Export Servers

+

Server definitions (and their groups) can be exported to a JSON file and +re-imported to the same or a different system to enable easy pre-configuration +of pgAdmin.

+
+

Using pgAdmin 4 GUI

+

To launch the Import/Export Servers… tool, navigate through Tools on the +menu bar to click on the Import/Export Servers option.

+Import/Export Servers step one page +
    +
  • Use the Import/Export field to select the Server Groups/Servers +to be imported or exported.

  • +
  • Use the Filename field to select the JSON file to import servers or create the +new file in case of Export where the servers to be exported in the JSON format.

  • +
  • Use the Remove all the existing servers? field to specify whether to remove all the +existing servers or not before importing the new selected servers. +This field is applicable only in case of Import Servers.

  • +
+

Click the Next button to continue, or the X button to close the wizard.

+Import/Export Servers step two page +
    +
  • Select the Server Groups/ Servers to be imported/exported.

  • +
+

Click the Next button to continue, or the X button to close the wizard.

+Import/Export Servers step three page +

Check the summary of the servers that are going to be imported/exported on the +Summary page.

+

Click the Finish button to close the wizard.

+
+
+

Using ‘setup.py’ command line script

+
+

Note

+

To export or import servers using setup.py script, you must use +the Python interpreter that is normally used to run pgAdmin to ensure +that the required Python packages are available. In most packages, this +can be found in the Python Virtual Environment that can be found in the +installation directory. When using platform-native packages, the system +installation of Python may be the one used by pgAdmin.

+
+
+

Exporting Servers

+

To export the servers defined in an installation, simply invoke setup.py with +the dump-servers command line option, followed by the name (and if required, +path) to the desired output file. By default, servers owned by the desktop mode +user will be dumped (pgadmin4@pgadmin.org by default - see the DESKTOP_USER +setting in config.py). This can be overridden with the --user command +line option. There can be multiple configurations of pgAdmin on the same system. +To dump the servers from specific pgAdmin config DB file, --sqlite-path option +can be used. It is also recommended to use this option when running pgAdmin in +desktop mode. By default SQLITE_PATH setting in config.py is taken. +For example:

+
/path/to/python /path/to/setup.py dump-servers output_file.json
+
+# or, to specify a non-default user name and auth source (the default is Internal):
+
+/path/to/python /path/to/setup.py dump-servers output_file.json --user user@example.com --auth_source ldap
+
+# to specify a pgAdmin config DB file:
+
+/path/to/python /path/to/setup.py dump-servers output_file.json --sqlite-path /path/to/pgadmin4.db
+
+
+

To export only certain servers, use the --server option and list one or +more server IDs. For example:

+
/path/to/python /path/to/setup.py dump-servers output_file.json --server 1 --server 2 --server 5
+
+
+
+
+

Importing Servers

+

To import the servers defined in a JSON file, simply invoke setup.py with +the load-servers command line option, followed by the name (and if required, +path) of the JSON file containing the server definitions. Servers will be owned +by the desktop mode user (pgadmin4@pgadmin.org by default - see the DESKTOP_USER +setting in config.py). This can be overridden with the --user command +line option. There can be multiple configurations of pgAdmin on the same system. +The default behaviour is for the imported servers to be added to the existent list, +which might lead to duplicates. This can be overridden with the --replace command +line option, which will replace the list of servers with the newly imported one. +To load the servers into a specific pgAdmin config DB file, --sqlite-path option +can be used. It is also recommended to use this option when running pgAdmin in +desktop mode. By default SQLITE_PATH setting in config.py is taken. For example:

+
/path/to/python /path/to/setup.py load-servers input_file.json
+
+# or, to replace the list of servers with the newly imported one:
+
+/path/to/python /path/to/setup.py load-servers input_file.json --replace
+
+# or, to specify a non-default user name and auth source (the default is Internal) to own the new servers:
+
+/path/to/python /path/to/setup.py load-servers input_file.json --user user@example.com
+
+# to specify a pgAdmin config DB file:
+
+/path/to/python /path/to/setup.py load-servers input_file.json --sqlite-path /path/to/pgadmin4.db
+
+
+

If any Servers are defined with a Server Group that is not already present in +the configuration database, the required Group will be created.

+
+
+

JSON format

+

The JSON file format used when importing or exporting servers is quite +straightforward and simply contains a list of servers, with a number of +attributes. The following attributes are required to be present in every server +definition: Name, Group, Port, Username, SSLMode, MaintenanceDB and one of Host, +HostAddr or Service.

+

Password fields cannot be imported or exported.

+

The following example shows both a minimally defined and a fully defined server:

+
{
+    "Servers": {
+        "1": {
+            "Name": "Minimally Defined Server",
+            "Group": "Server Group 1",
+            "Port": 5432,
+            "Username": "postgres",
+            "Host": "localhost",
+            "SSLMode": "prefer",
+            "MaintenanceDB": "postgres"
+        },
+        "2": {
+            "Name": "Fully Defined Server",
+            "Group": "Server Group 2",
+            "Host": "host.domain.com",
+            "HostAddr": "192.168.1.2",
+            "Port": 5432,
+            "MaintenanceDB": "postgres",
+            "Username": "postgres",
+            "Role": "my_role_name",
+            "SSLMode": "require",
+            "Comment": "This server has every option configured in the JSON",
+            "DBRestriction": "live_db test_db",
+            "PassFile": "/path/to/pgpassfile",
+            "SSLCert": "/path/to/sslcert.crt",
+            "SSLKey": "/path/to/sslcert.key",
+            "SSLRootCert": "/path/to/sslroot.crt",
+            "SSLCrl": "/path/to/sslcrl.crl",
+            "SSLCompression": 1,
+            "Shared": false,
+            "SharedUsername": "postgres",
+            "BGColor": "#ff9900",
+            "FGColor": "#000000",
+            "Service": "postgresql-10",
+            "Timeout": 60,
+            "UseSSHTunnel": 1,
+            "TunnelHost": "192.168.1.253",
+            "TunnelPort": 22,
+            "TunnelUsername": "username",
+            "TunnelAuthentication": 0,
+            "PasswordExecCommand": "echo 'test'",
+            "PasswordExecExpiration": 100
+        }
+    }
+}
+
+
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/index.html b/pgsql/pgAdmin 4/docs/en_US/html/index.html new file mode 100644 index 0000000000000000000000000000000000000000..24d33fc375858b6acdd9e84d9864c5bb5b1ddca3 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/index.html @@ -0,0 +1,363 @@ + + + + + + + + + + pgAdmin 4 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + +
+
+
+
+ +
+

pgAdmin 4

+pgAdmin Logo +

Welcome to pgAdmin 4. pgAdmin is the leading Open Source management tool for +Postgres, the world’s most advanced Open Source database. pgAdmin 4 is designed +to meet the needs of both novice and experienced Postgres users alike, providing +a powerful graphical interface that simplifies the creation, maintenance and use +of database objects.

+
+ +
+
+

Note

+

Postgres, PostgreSQL and the Slonik Logo are trademarks or +registered trademarks of the PostgreSQL Community Association of Canada, and used with their permission.

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/index_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/index_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..eadc75443eb57d2768f0cff4d44c42dd9b5da493 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/index_dialog.html @@ -0,0 +1,265 @@ + + + + + + + + + + Index Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Index Dialog

+

Use the Index dialog to create an index on a specified table or materialized +view.

+

The Index dialog organizes the development of a index through the following +dialog tabs: General, Definition, and Columns. The SQL tab displays the SQL code +generated by dialog selections.

+Index dialog general tab +

Use the fields in the General tab to identify the index:

+
    +
  • Use the Name field to add a descriptive name for the index. The name will +be displayed in the pgAdmin tree control.

  • +
  • Use the drop-down listbox next to Tablespace to select the tablespace in +which the index will reside.

  • +
  • Store notes about the index in the Comment field.

  • +
+

Click the Definition tab to continue.

+Index dialog definition tab +

Use the fields in the Definition tab to define the index:

+
    +
  • Use the drop-down listbox next to Access Method to select an index type:

    +
    +
      +
    • Select btree to create a B-tree index. A B-tree index may improve +performance when managing equality and range queries on data that can be +sorted into some ordering (the default).

    • +
    • Select hash to create a hash index. A hash index may improve +performance when managing simple equality comparisons.

    • +
    • Select gist to create a GiST index. A GiST index may improve +performance when managing two-dimensional geometric data types and +nearest-neighbor searches.

    • +
    • Select gin to create a GIN index. A GIN index may improve +performance when managing values with more than one key.

    • +
    • Select spgist to create a space-partitioned GiST index. A SP-GiST index +may improve performance when managing non-balanced data structures.

    • +
    • Select brin to create a BRIN index. A BRIN index may improve +performance when managing minimum and maximum values and ranges.

    • +
    +
    +
  • +
  • Use the Fill Factor field to specify a fill factor for the index. The fill +factor specifies how full the selected method will try to fill each index +page.

  • +
  • Use the Gin pending list limit field to specify the maximum size of a GIN index’s pending list, which is used +when fastupdate is enabled. This value is specified in kilobytes.

  • +
  • Use the Pages per range field to specify the number of table blocks that make up one block range +for each entry of a BRIN index.

  • +
  • Select Buffering to specify whether the buffering build technique is used to build the index. The default is +Auto

  • +
  • Move the switch next to Deduplicate items? towards the right position to control usage of the B-tree +deduplication technique. The default is Yes. This option is available only on PostgreSQL 13 and above.

  • +
  • Move the switch next to Fast update? towards the right position to control usage of the fast update technique. +The default is Yes.

  • +
  • Move the switch next to Autosummarize towards the right position to define whether a summarization run is +queued for the previous page range whenever an insertion is detected on the next one. The default is No

  • +
  • Move the switch next to Unique? towards the right position to check for duplicate values +in the table when the index is created and when data is added. The default is No.

  • +
  • Move the switch next to NULLs not distinct? towards the right position to treat null values as not distinct. +The default is*No*. This option is available only on PostgreSQL 15 and above.

  • +
  • Move the Clustered? switch to the Yes position to instruct the server to +cluster the table.

  • +
  • Move the Concurrent build? switch to the Yes position to build the index +without taking any locks that prevent concurrent inserts, updates, or deletes +on the table.

  • +
  • Use the Constraint field to provide a constraint expression; a constraint +expression limits the entries in the index to those rows that satisfy the +constraint.

  • +
+

Click the Columns tab to continue.

+Index dialog columns tab +

Use the fields in the Columns tab to specify which column(s) or expression(s) +the index queries. Use the Is expression ? switch to enable +expression sql input. Use the drop-down listbox next to Column +to select a column. Once the Column is selected or the Expression is +entered then click the Add icon (+) to provide details of the action on the +column/expression:

+
    +
  • The Col/Exp field is populated with the selection made in the Column +drop-down listbox or the Expression entered.

  • +
  • If enabled, use the drop-down listbox to select an available Operator class +to specify the type of action performed on the column.

  • +
  • If enabled, use the drop-down listbox to select Sort order:

    +
    +
      +
    • Select ASC to specify an ascending sort order (the default);

    • +
    • Select DESC to specify a descending sort order.

    • +
    +
    +
  • +
  • If enabled, use the drop-down listbox to select Nulls:

    +
    +
      +
    • Select First to specify nulls sort before non-nulls;

    • +
    • Select Last to specify nulls sort after non-nulls (the default).

    • +
    +
    +
  • +
  • Use the drop-down listbox in the Collation field to select a collation to +use for the index.

  • +
+

Use Include columns field to specify columns for INCLUDE clause of the +constraint. This option is available in Postgres 11 and later.

+

Click the SQL tab to continue.

+

Your entries in the Index dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any +changes to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Index dialog:

+Index dialog sql tab +

The example shown demonstrates creating an index named index_sal that indexes +the values in the job column of the jobhist table.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/kerberos.html b/pgsql/pgAdmin 4/docs/en_US/html/kerberos.html new file mode 100644 index 0000000000000000000000000000000000000000..b56064207ba38869459cd1e7bfab9d8aaf200671 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/kerberos.html @@ -0,0 +1,299 @@ + + + + + + + + + + Enabling Kerberos Authentication — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Enabling Kerberos Authentication

+

Prerequisite: Kerberos understanding and setup

+

Reference: https://web.mit.edu/kerberos/

+

To configure Kerberos authentication, you must setup your Kerberos Server and +obtain a ticket on the client using kinit.

+

Note: Active Directory users with Kerberos support do not require kinit.

+

To enable Kerberos authentication for pgAdmin, you must configure the +Kerberos settings in config_local.py or config_system.py +(see the config.py documentation) on the +system where pgAdmin is installed in Server mode. You can copy these settings +from config.py file and modify the values for the following parameters.

+ ++++ + + + + + + + + + + + + + + + + +

Parameter

Description

AUTHENTICATION_SOURCES

The default value for this parameter is internal. +To enable Kerberos authentication, you must include kerberos in the +list of values for this parameter. you can modify the value as follows:

+
    +
  • [‘kerberos’]: pgAdmin will use only Kerberos authentication.

  • +
  • [‘kerberos’, ‘internal’]: pgAdmin will first try to authenticate the user +through kerberos. If that authentication fails, then it will return back +to the login page where you need to provide internal pgAdmin user +credentials for authentication.

  • +
+

KERBEROS_AUTO_CREATE_USER

Set the value to True if you want to +automatically create a pgAdmin user corresponding to a successfully +authenticated Kerberos user. Please note that password is not stored in the +pgAdmin database.

KRB_APP_HOST_NAME

Specify the name of pgAdmin webserver hostname. +Please note that if it is not set, it will take the value of +default_server parameter.

+
+

Keytab file for HTTP Service

+
    +
  • Generate the Keytab file for the HTTP service principal HTTP/<host-name>@realm, +and copy it to the pgAdmin webserver machine. Ensure that the operating system +user owning the pgAdmin webserver is the owner of this file and should be +accessible by that user.

  • +
  • Please note that either you should set default_keytab_name parameter in +krb5.conf file or the environment variable KRB5_KTNAME. If not set then +explicitly set KRB_KTNAME to the location of your Keytab file in the +config_local.py or config_system.py file.

  • +
+
+
+

Apache HTTPD Configuration

+

If the pgAdmin server is under the Apache Server, then you need to add the +following parameters in Directory directive of +Apache HTTPD Configuration:

+
+
    +
  • WSGIScriptReloading On

  • +
  • WSGIPassAuthorization On

  • +
+
+
+
+

Browser settings to configure Kerberos Authentication

+

You need to configure the browser settings on the client machine to use +Kerberos authentication via SPNEGO.

+
    +
  • For Mozilla Firefox

    +
      +
    • Open the low level Firefox configuration page by entering about:config in +the address bar.

    • +
    • In the Search text box, enter: network.negotiate-auth.trusted-uris

    • +
    • Double-click the network.negotiate-auth.trusted-uris preference and enter +the hostname or the domain of the web server that is protected by Kerberos +HTTP SPNEGO. Separate multiple domains and hostnames with a comma.

    • +
    • Click OK.

    • +
    +
  • +
  • For Google Chrome

    +
      +
    • On Windows:

      +
        +
      • Open the Control Panel to access the Internet Options dialog.

      • +
      • Select the Security tab.

      • +
      • Select the Local Intranet zone and click the Sites button.

      • +
      • Make sure that the first two options, Include all local (intranet) sites +not listed in other zones and Include all sites that bypass the proxy +server are checked.

      • +
      • Click Advanced and add the names of the domains that are protected by +Kerberos HTTP SPNEGO, one at a time, to the list of websites. For example, +myhost.example.com. Click Close.

      • +
      • Click OK to save your configuration changes.

      • +
      +
    • +
    • On Linux or macOS:

      +
        +
      • Add the –auth-server-whitelist parameter to the google-chrome command. +For example, to run Chrome from a Linux prompt, run the google-chrome +command as follows:

      • +
      +
      google-chrome --auth-server-whitelist = "hostname/domain"
      +
      +
      +
    • +
    +
  • +
+
+
+

PostgreSQL Server settings to configure Kerberos Authentication

+
    +
  • To connect the PostgreSQL server with Kerberos authentication, GSSAPI support +has to be enabled when PostgreSQL is built and the necessary +configuration +has to be in place.

  • +
  • In pgAdmin you need to enable Kerberos authentication for the PostgreSQL +server by setting “Kerberos authentication” flag to True in the Server dialog. +Once it is enabled, pgAdmin will not prompt for a password and will try to +connect to the PostgreSQL server using Kerberos.

  • +
  • Note that, you have to login into pgAdmin with Kerberos authentication to +then connect to PostgreSQL using Kerberos.

  • +
+
+
+

Master Password

+

In the multi user mode, pgAdmin uses user’s login password to encrypt/decrypt the PostgreSQL server password. +In the Kerberos authentication, the pgAdmin user does not have the password, so we need an encryption key to store +the PostgreSQL server password for the servers which are not configured to use the Kerberos authentication. +To accomplish this, set the configuration parameter MASTER_PASSWORD to True, so upon setting the master password, +it will be used as an encryption key while storing the password. If it is False, the server password can not be stored.

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/keyboard_shortcuts.html b/pgsql/pgAdmin 4/docs/en_US/html/keyboard_shortcuts.html new file mode 100644 index 0000000000000000000000000000000000000000..e6fb62ec23cc4c0acb5c307c7cf9d351faac0656 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/keyboard_shortcuts.html @@ -0,0 +1,670 @@ + + + + + + + + + + Keyboard Shortcuts: — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Keyboard Shortcuts:

+

Keyboard shortcuts are provided in pgAdmin to allow easy access to specific +functions. Alternate shortcuts can be configured through File > Preferences if +desired.

+
+

Main Browser Window

+

When using main browser window, the following keyboard shortcuts are available:

+ ++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Shortcut for all platforms

Function

Shift+Ctrl+a

Add grid row

Shift+Alt+b

Object explorer

Shift+Alt+n

Create object

Shift+Alt+d

Delete object

Shift+Alt+g

Direct debugging

Shift+Alt+e

Edit object properties

Shift+Alt+f

File main menu

Shift+Alt+h

Help main menu

Shift+Alt+o

Object main menu

Shift+Alt+c

Open context menu

Shift+Alt+q

Open query tool

Shift+Ctrl+f

Quick Search

F5

Refresh object explorer

Shift+Alt+s

Search objects

Shift+Alt+[

Tabbed panel backward

Shift+Alt+]

Tabbed panel forward

Shift+Alt+l

Tools main menu

Shift+Alt+v

View data

+
+
+

Property Grid Controls

+

Use the shortcuts below when working with property grid controls:

+ ++++ + + + + + + + + + + + + + + + + + + + + + + +

Shortcut for all platforms

Function

Control+Shift+A

Add row in Grid

Tab

Move focus to the next control

Shift+Tab

Move focus to the previous control

Return

Pick the selected an item in a combo box

Control+Shift+A

Add row in Grid

+
+
+

SQL Editors

+

When using the syntax-highlighting SQL editors, the following shortcuts are available:

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Shortcut (Windows/Linux)

Shortcut (Mac)

Function

Alt + Left

Option + Left

Move to the beginning of the line

Alt + Right

Option + Right

Move to the end of the line

Ctrl + Alt + Left

Cmd + Option + Left

Move left one word

Ctrl + Alt + Right

Cmd + Option + Right

Move right one word

Ctrl + /

Cmd + /

Comment selected code (Inline)

Ctrl + .

Cmd + .

Uncomment selected code (Inline)

Ctrl + Shift + /

Cmd + Shift + /

Comment/Uncomment code (Block)

Ctrl + a

Cmd + a

Select all

Ctrl + c

Cmd + c

Copy selected text to the clipboard

Ctrl + r

Cmd + r

Redo last edit un-done

Ctrl + v

Cmd + v

Paste text from the clipboard

Ctrl + z

Cmd + z

Undo last edit

Tab

Tab

Indent selected text

Shift + Tab

Shift + Tab

Un-indent selected text

Ctrl + l

Cmd + l

Go to line, column

Ctrl + Space

Ctrl + Space

Auto-complete

Ctrl + f

Cmd + f

Find

Ctrl + g

Cmd + g

Find next

Ctrl + Shift + g

Cmd + Shift + g

Find previous

Ctrl + Shift + f

Cmd + Shift + f

Replace

+
+
+

Query Tool

+

When using the Query Tool, the following shortcuts are available:

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Shortcut (Windows/Linux)

Shortcut (Mac)

Function

<accesskey> + q

<accesskey> + q

Cancel query

<accesskey> + t

<accesskey> + t

Connection status

<accesskey> + d

<accesskey> + d

Delete rows

<accesskey> + x

<accesskey> + x

Execute options

<accesskey> + f

<accesskey> + f

Filter dialog

<accesskey> + i

<accesskey> + i

Filter options

<accesskey> + n

<accesskey> + n

Find options

<accesskey> + o

<accesskey> + o

Open file

<accesskey> + p

<accesskey> + p

Paste rows

<accesskey> + r

<accesskey> + r

Rows limit

<accesskey> + s

<accesskey> + s

Save file

Ctrl + Alt + L

Ctrl + option + L

Clear query

Shift + Ctrl + m

Shift + Ctrl + m

Commit

F8

F8

Download Results

Shift + F7

Shift + F7

EXPLAIN ANALYZE query

F7

F7

EXPLAIN query

F5

F5

Execute query

Shift + Alt + ]

Shift + option + ]

Next tab

Shift + Alt + [

Shift + option + [

Previous tab

Shift + Ctrl + r

Shift + Ctrl + r

Rollback

F6

F6

Save data changes

Shift + Alt + Tab

Shift + option +Tab

Switch Panel

Shift + Ctrl + u

Shift + Ctrl + u

Toggle case of selected text

+
+
+

Debugger

+

When using the Debugger, the following shortcuts are available:

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Shortcut (Windows/Linux)

Shortcut (Mac)

Function

<accesskey> + x

<accesskey> + x

Clear all breakpoints

<accesskey> + c

<accesskey> + c

Continue/Start

<accesskey> + i

<accesskey> + i

Step into

<accesskey> + o

<accesskey> + o

Step over

<accesskey> + s

<accesskey> + s

Stop

<accesskey> + t

<accesskey> + t

Toggle breakpoint

Shift + Alt + q

Shift + option + q

Edit grid values

Shift + Alt + ]

Shift + option + ]

Next tab

Shift + Alt + [

Shift + option + ]

Previous tab

Shift + Alt + Tab

Shift + option +Tab

Switch Panel

+
+
+

ERD Tool

+

When using the ERD Tool, the following shortcuts are available:

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Shortcut (Windows/Linux)

Shortcut (Mac)

Function

Ctrl + Alt + a

Ctrl + option + a

Add table

Ctrl + Alt + n

Ctrl + option + n

Add/Edit note

Ctrl + Alt + l

Ctrl + option + l

Auto align

Ctrl + Alt + c

Ctrl + option + c

Clone table

Ctrl + Alt + i

Ctrl + option + i

Download image

Ctrl + Alt + d

Ctrl + option + d

Drop table

Ctrl + Alt + e

Ctrl + option + e

Edit table

Ctrl + Alt + s

Ctrl + option + s

Generate SQL

Ctrl + Alt + m

Ctrl + option + m

Many to many link

Ctrl + Alt + o

Ctrl + option + o

One to many link

Ctrl + o

Ctrl + o

Open project

Ctrl + s

Ctrl + s

Save project

Shift + Ctrl + s

Shift + Ctrl + s

Save project as

Ctrl + Alt + t

Ctrl + option + t

Show more/fewer details

Shift + Alt + +

Shift + option + +

Zoom in

Shift + Alt + -

Shift + option + -

Zoom out

Shift + Alt + f

Shift + option + f

Zoom to fit

+
+
+

Inner Tab and Panel Navigation

+

When using the Query Tool and Debugger, the following shortcuts are available +for inner panel navigation:

+
+
+

Access Key

+

<accesskey> is browser and platform dependant. The following table lists the +default access keys for supported browsers.

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Windows

Linux

Mac

Edge

Alt

Chrome

Alt

Alt

Ctrl + Option

Firefox

Alt + Shift

Alt + Shift

Ctrl + Option

Safari

Alt

Ctrl + Option

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/language_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/language_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..75e7b14f5c1cc801109363991be7fa2e11c55d63 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/language_dialog.html @@ -0,0 +1,233 @@ + + + + + + + + + + Language Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Language Dialog

+

Use the CREATE LANGUAGE dialog to register a new procedural language.

+

The Language dialog organizes the registration of a procedural language +through the following dialog tabs: General, Definition, and Security. +The SQL tab displays the SQL code generated by dialog selections.

+Language dialog general tab +

Use the fields in the General tab to identify a language:

+
    +
  • Use the drop-down listbox next to Name to select a language script.

  • +
  • Use the drop-down listbox next to Owner to select a role.

  • +
  • Store notes about the language in the Comment field.

  • +
+

Click the Definition tab to continue.

+Language dialog definition tab +

Use the fields in the Definition tab to define parameters:

+
    +
  • Move the Trusted? switch to the No position to specify only users with +PostgreSQL superuser privilege can use this language. The default is Yes.

  • +
  • When enabled, use the drop-down listbox next to Handler Function to select +the function that will be called to execute the language’s functions.

  • +
  • When enabled, use the drop-down listbox next to Inline Function to select +the function that will be called to execute an anonymous code block (DO +command) in this language.

  • +
  • When enabled, use the drop-down listbox next to Validator Function to +select the function that will be called when a new function in the language +is created, to validate the new function.

  • +
+

Click the Security tab to continue.

+Language dialog security tab +

Use the Security tab to assign privileges and define security labels.

+

Use the Privileges panel to assign privileges to a role. Click the Add icon +(+) to set privileges for database objects:

+
    +
  • Select the name of the role from the drop-down listbox in the Grantee field.

  • +
  • Click inside the Privileges field. Check the boxes to the left of one or +more privileges to grant the selected privilege to the specified user.

  • +
  • The current user, who is the default grantor for granting the privilege, is displayed in the Grantor field.

  • +
+

Click the Add icon (+) to assign additional privileges; to discard a +privilege, click the trash icon to the left of the row and confirm deletion in +the Delete Row popup.

+

Use the Security Labels panel to define security labels applied to the +function. Click the Add icon (+) to add each security label selection:

+
    +
  • Specify a security label provider in the Provider field. The named provider +must be loaded and must consent to the proposed labeling operation.

  • +
  • Specify a a security label in the Security Label field. The meaning of a +given label is at the discretion of the label provider. PostgreSQL places no +restrictions on whether or how a label provider must interpret security +labels; it merely provides a mechanism for storing them.

  • +
+

Click the Add icon (+) to assign additional security labels; to discard a +security label, click the trash icon to the left of the row and confirm deletion +in the Delete Row popup.

+

Click the SQL tab to continue.

+

Your entries in the Language dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Language dialog:

+Language dialog sql tab +

The example shown demonstrates creating the trusted procedural language named mylan.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/ldap.html b/pgsql/pgAdmin 4/docs/en_US/html/ldap.html new file mode 100644 index 0000000000000000000000000000000000000000..4afbaec1b61ae75e6627d138935b28952af3de03 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/ldap.html @@ -0,0 +1,293 @@ + + + + + + + + + + Enabling LDAP Authentication — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Enabling LDAP Authentication

+

To enable LDAP authentication for pgAdmin, you must configure the LDAP +settings in the config_local.py or config_system.py file (see the +config.py documentation) on the system where pgAdmin is +installed in Server mode. You can copy these settings from config.py file +and modify the values for the following parameters:

+

There are 3 ways to configure LDAP:

+
    +
  • Bind as pgAdmin user

  • +
  • Anonymous bind

  • +
  • Dedicated user bind

  • +
+ ++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Parameter

Description

AUTHENTICATION_SOURCES

The default value for this parameter is internal. +To enable LDAP authentication, you must include ldap in the list of values +for this parameter. you can modify the value as follows:

+
    +
  • [‘ldap’]: pgAdmin will use only LDAP authentication.

  • +
  • [‘ldap’, ‘internal’]: pgAdmin will first try to authenticate the user through +LDAP. If that authentication fails, then internal user entries of pgAdmin +will be used for authentication.

  • +
  • [‘internal’, ‘ldap’]: pgAdmin will first try to authenticate the user +through internal user entries. If that authentication fails, then LDAP +authentication will be used.

  • +
+

LDAP_AUTO_CREATE_USER

Specifies if you want to automatically create a pgAdmin +user corresponding to the LDAP user credentials. Please note that LDAP password +is not stored in the pgAdmin database.

LDAP_CONNECTION_TIMEOUT

Specifies the connection timeout (in seconds) for LDAP +authentication.

LDAP_SERVER_URI

An LDAP URI is a combination of connection protocol +(ldap or ldaps), IP address/hostname and port of the directory server that you +want to connect to. For example, ‘ldap://172.16.209.35:389’ is a valid +LDAP_SERVER_URI where ldap is the connection protocol, 172.16.209.35 is the IP +address and 389 is the port. Port 636 is used for the ldaps communication protocol.

LDAP_USERNAME_ATTRIBUTE

Specifies the LDAP attribute that contains the +usernames. For LDAP authentication, you need to enter the value of that +particular attribute as username. For example, if you set the value of +LDAP_USERNAME_ATTRIBUTE as ‘cn’ and you have defined ‘cn=admin’ in your LDAP server +entries, you should be able to authenticate by entering ‘admin’ in the +Email Address / Username field and its corresponding password in the Password +field.

LDAP_SEARCH_BASE_DN

Specifies the distinguished name (DN) for the top-most user +directory that you want to search. You can use this parameter for limiting the search +request to a specific group of users. For example, if you want to search only within +the Organizational Unit named sales, you can define the value for LDAP_SEARCH_BASE_DN +parameter as following: +LDAP_SEARCH_BASE_DN = ‘ou=sales,dc=example,dc=com’

+

This is an optional parameter only while binding as pgAdmin user. +If you do not specify any value for LDAP_SEARCH_BASE_DN, then the value for +LDAP_BASE_DN will be considered for the same.

+

LDAP_SEARCH_FILTER

Defines the criteria to retrieve matching entries in an +LDAP search request. For example, LDAP_SEARCH_FILTER = ‘(objectclass=HR)’ setting +searches only for users having HR as their objectClass attribute.

LDAP_SEARCH_SCOPE

Indicates the set of entries at or below the Base DN that +maybe considered as potential matches for a search request. You can specify the +scope of a search as either a base, level, or subtree search. A base search +limits the search to the base object. A level search is restricted to the immediate +children of a base object, but excludes the base object itself. A subtree search +includes all child objects as well as the base object.

LDAP_DN_CASE_SENSITIVE

Indicates whether the DN (Distinguished Names) are case sensitive or not. +Possible values are True or False. By default is set to False.

LDAP_USE_STARTTLS

Specifies if you want to use Transport Layer Security (TLS) +for secure communication between LDAP clients and LDAP servers. If you specify +the connection protocol in LDAP_SERVER_URI as ldaps, this parameter is ignored.

LDAP_CA_CERT_FILE

Specifies the path to the trusted CA certificate file. This +parameter is applicable only if you are using ldaps as connection protocol or +you have set LDAP_USE_STARTTLS parameter to True.

LDAP_CERT_FILE

Specifies the path to the server certificate file. This parameter +is applicable only if you are using ldaps as connection protocol or you have +set LDAP_USE_STARTTLS parameter to True.

LDAP_KEY_FILE

Specifies the path to the server private key file. This parameter +is applicable only if you are using ldaps as connection protocol or you have +set LDAP_USE_STARTTLS parameter to True.

LDAP_IGNORE_MALFORMED_SCHEMA

Some flaky LDAP servers returns malformed schema. +If this parameter set to True, no exception will be raised and schema is thrown away +but authentication will be done. This parameter should remain False, as recommended.

Bind as pgAdmin user

LDAP_BASE_DN

Specifies the base DN from where a server will start the search +for users. For example, an LDAP search for any user will be performed by the server +starting at the base DN (dc=example,dc=com). When the base DN matches, the full +DN (cn=admin,dc=example,dc=com) is used to bind with the supplied password.

Anonymous bind

LDAP_ANONYMOUS_BIND

Set this parameter to True for anonymous binding. +After the connection is made, the pgadmin login user will be further authenticated +by the username and password provided at the login screen.

Dedicated user bind

LDAP_BIND_USER

The account of the user to log in for simple bind. +Set this parameter to allow the connection to bind using a dedicated user. +After the connection is made, the pgadmin login user will be further +authenticated by the username and password provided at the login screen. +at the login screen.

LDAP_BIND_PASSWORD

Password for simple bind. +Specify the value if you have set the LDAP_BIND_USER parameter.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/licence.html b/pgsql/pgAdmin 4/docs/en_US/html/licence.html new file mode 100644 index 0000000000000000000000000000000000000000..e9e0899e5e0a73d622851718c4a0b47a62c26143 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/licence.html @@ -0,0 +1,136 @@ + + + + + + + + + + Licence — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Licence

+

pgAdmin is released under the +PostgreSQL Licence, which is a +liberal Open Source licence similar to BSD or MIT, and approved by the Open +Source Initiative. The copyright for the project source code, website and +documentation is attributed to the +pgAdmin Development Team

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/login.html b/pgsql/pgAdmin 4/docs/en_US/html/login.html new file mode 100644 index 0000000000000000000000000000000000000000..0788444a433145075ac813bb28378e8902f5f871 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/login.html @@ -0,0 +1,204 @@ + + + + + + + + + + Login Page — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Login Page

+

Use the Login page to log in to pgAdmin:

+pgAdmin login page +

Use the fields in the Login page to authenticate your connection. There are +two ways to authenticate your connection:

+
    +
  • From pgAdmin version 4.21 onwards, support for LDAP authentication +has been added. If LDAP authentication has been enabled for your pgAdmin +application, you can use your LDAP credentials to log in to pgAdmin:

    +
      +
    • Provide the LDAP username in the Email Address/Username field.

    • +
    • Provide your LDAP password in the Password field.

    • +
    +
  • +
  • Alternatively, you can use the following information to log in to pgAdmin:

    +
      +
    • Provide the email address associated with your account in the +Email Address/Username field.

    • +
    • Provide your password in the Password field.

    • +
    +
  • +
+

Click the Login button to securely log into pgAdmin.

+

Please note that if the pgAdmin server is restarted, then you will be logged +out. You need to re-login to continue.

+
+

Recovering a Lost Password

+

If you cannot supply your password, click the Forgotten your password? button +to launch a password recovery utility.

+pgAdmin recover login password +
    +
  • Provide the email address associated with your account in the Email Address +field.

  • +
  • Click the Recover Password button to initiate recovery. An email, with +directions on how to reset a password, will be sent to the address entered in +the Email Address field.

  • +
+

If you have forgotten the email associated with your account, please contact +your administrator.

+

Please note that your LDAP password cannot be recovered using this page. If +you enter your LDAP username in the Email Address/Username field, and then +enter your email to recover your password, an error message will be displayed +asking you to contact the LDAP administrator to recover your LDAP password.

+
+
+

Avoiding a bruteforce attack

+

You have the possibility to lock an account by setting MAX_LOGIN_ATTEMPTS +once it has reached the maximum number of login attempts. +You can disable this feature by setting the value to zero.

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/maintenance_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/maintenance_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..34b5d5f9dc2d0d31398caa572ae3cb3682340440 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/maintenance_dialog.html @@ -0,0 +1,231 @@ + + + + + + + + + + Maintenance Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Maintenance Dialog

+

Use the Maintenance dialog to VACUUM, ANALYZE, REINDEX or CLUSTER a database +or selected database objects.

+

While this utility is useful for ad-hoc maintenance purposes, you are encouraged +to perform automatic VACUUM jobs on a regular schedule.

+

Select a button next to Maintenance operation to specify the type of +maintenance:

+Maintenance dialog +
    +
  • Click VACUUM to scan the selected database or table to reclaim storage used +by dead tuples.

    +
    +
      +
    • Move the FULL switch to the Yes position to compact tables by writing +a completely new version of the table file without dead space.

    • +
    • Move the FREEZE switch to the Yes position to freeze data in a table +when it will have no further updates.

    • +
    • Move the ANALYZE switch to the Yes position to issue ANALYZE commands +whenever the content of a table has changed sufficiently.

    • +
    • Move the DISABLE PAGE SKIPPING switch to the Yes position to disables +all page-skipping behavior.

    • +
    • Move the SKIP LOCKED switch to the Yes position to specifies that +VACUUM should not wait for any conflicting locks to be released when +beginning work on a relation. This option is available from v12 onwards.

    • +
    • Move the TRUNCATE switch to the Yes position to specifies that VACUUM +should attempt to truncate off any empty pages at the end of the table and +allow the disk space for the truncated pages to be returned to the operating +system. This option is available from v12 onwards.

    • +
    • Move the PROCESS TOAST switch to the Yes position to specifies that +VACUUM should attempt to process the corresponding TOAST table for each +relation, if one exists. This option is available from v14 onwards.

    • +
    • Move the PROCESS MAIN switch to the Yes position to specifies that +VACUUM should attempt to process the main relation. This option is available +from v16 onwards.

    • +
    • Move the SKIP DATABASE STATS switch to the Yes position to specifies +that VACUUM should skip updating the database-wide statistics about oldest +unfrozen XIDs. This option is available from v16 onwards.

    • +
    • Move the ONLY DATABASE STATS switch to the Yes position to specifies +that VACUUM should do nothing except update the database-wide statistics +about oldest unfrozen XIDs . This option is available from v16 onwards.

    • +
    • Use the INDEX CLEANUP field to force VACUUM to process indexes when there +are more than zero dead tuples.

    • +
    • Use the PARALLEL field to specify index vacuum and index cleanup phases +of VACUUM in parallel using integer background workers. This option is +available from v13 onwards.

    • +
    • Use the BUFFER USAGE LIMIT field to specifies the Buffer Access Strategy +ring buffer size for VACUUM. This size is used to calculate the number of +shared buffers which will be reused as part of this strategy. This option +is available from v16 onwards

    • +
    +
    +
  • +
+Maintenance dialog +
    +
  • Click ANALYZE to update the stored statistics used by the query planner. +This enables the query optimizer to select the fastest query plan for optimal +performance.

    +
    +
      +
    • Move the SKIP LOCKED switch to the Yes position to specifies that +ANALYZE should not wait for any conflicting locks to be released when +beginning work on a relation. This option is available from v12 onwards.

    • +
    • Use the BUFFER USAGE LIMIT field to specifies the Buffer Access Strategy +ring buffer size for ANALYZE. This size is used to calculate the number of +shared buffers which will be reused as part of this strategy. This option +is available from v16 onwards

    • +
    +
    +
  • +
+Maintenance dialog +
    +
  • Click REINDEX to rebuild any index in case it has degenerated due to the +insertion of unusual data patterns. This happens, for example, if you insert +rows with increasing index values, and delete low index values.

    +
    +
      +
    • Move the SYSTEM switch to the Yes position to recreate all indexes +on system catalogs within the current database. This option is enabled +only when database object is selected.

    • +
    • Move the CONCURRENTLY switch to the Yes position to rebuild the index +without taking any locks that prevent concurrent inserts, updates, or +deletes on the table. This option is available from v12 onwards.

    • +
    • Use the TABLESPACE field to specifies that indexes will be rebuilt on +a new tablespace. This option is available from v14 onwards.

    • +
    +
    +
  • +
+Maintenance dialog +
    +
  • Click CLUSTER to instruct PostgreSQL to cluster the selected table.

  • +
+

To exclude status messages from the process output, move the Verbose Messages +switch to the No position; by default, status messages are included.

+

When you’ve completed the dialog, click OK to start the background process; +to exit the dialog without performing maintenance operations, click Cancel.

+

pgAdmin will run the maintenance process in background. You can view all the background +process with there running status and logs on the Processes +tab.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/management_basics.html b/pgsql/pgAdmin 4/docs/en_US/html/management_basics.html new file mode 100644 index 0000000000000000000000000000000000000000..86d1d0fb723544d7248f033aa0e9f79282aa2d8c --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/management_basics.html @@ -0,0 +1,142 @@ + + + + + + + + + + Management Basics — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Management Basics

+

pgAdmin provides point and click dialogs that help you perform server management +functions. Dialogs simplify tasks such as managing named restore points, +granting user privileges, and performing VACUUM, ANALYZE and REINDEX functions.

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/managing_cluster_objects.html b/pgsql/pgAdmin 4/docs/en_US/html/managing_cluster_objects.html new file mode 100644 index 0000000000000000000000000000000000000000..c3d5c6e78b96481e4fa45a190ac5ea45558ac83c --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/managing_cluster_objects.html @@ -0,0 +1,145 @@ + + + + + + + + + + Managing Cluster Objects — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Managing Cluster Objects

+

Some object definitions reside at the cluster level; pgAdmin 4 provides dialogs +that allow you to create these objects, manage them, and control their +relationships to each other. To access a dialog that allows you to create a +database object, right-click on the object type in the pgAdmin tree control, +and select the Create option for that object. For example, to create a new +database, right-click on the Databases node, and select Create Database…

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/managing_database_objects.html b/pgsql/pgAdmin 4/docs/en_US/html/managing_database_objects.html new file mode 100644 index 0000000000000000000000000000000000000000..b92378ba6973c6a49066f96a54d5791d79d94853 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/managing_database_objects.html @@ -0,0 +1,191 @@ + + + + + + + + + + Managing Database Objects — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Managing Database Objects

+

pgAdmin 4 provides simple but powerful dialogs that you can use to design and +create database objects. Each dialog contains a series of tabs that you use to +describe the object that will be created by the dialog; the SQL tab displays the +SQL command that the server will execute when creating the object.

+

To access a dialog that allows you to create a database object, right-click on +the object type in the pgAdmin tree control, and select the Create option for +that object. For example, to create a new cast, right-click on the Casts +node, and select Create Cast…

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/master_password.html b/pgsql/pgAdmin 4/docs/en_US/html/master_password.html new file mode 100644 index 0000000000000000000000000000000000000000..1859961d0b27876ad096e23665350c11c60522c8 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/master_password.html @@ -0,0 +1,189 @@ + + + + + + + + + + Master Password — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Master Password

+
+

Note

+

pgAdmin 4 uses the operating system password store by default to store the saved server passwords in desktop mode from version 7.2 onwards and Master password will not be required. +If the operating system password store is not available then pgAdmin 4 will continue to use a master password as per the configuration settings.

+
+

A master password is required to secure and later unlock the saved server +passwords. This is applicable for desktop mode and in server mode if authentication source contains OAuth2 or Kerberos or Webserver.

+
    +
  • You are prompted to enter the master password when you open the window for +the first time after starting the application.

  • +
  • Once you set the master password, all the existing saved passwords will be +re-encrypted using the master password.

  • +
  • The server passwords which are saved in the SQLite DB file or External +Database are encrypted and decrypted using the master password.

  • +
+Set master password +
+

Note

+

pgAdmin aims to be secure by default, however, you can disable the master +password by setting the configuration parameter MASTER_PASSWORD_REQUIRED=False. +See The config.py File for more information on configuration parameters and how +they can be changed or enforced across an organisation.

+
+
+

Note

+

If the master password is disabled, then all the saved passwords will +be removed.

+
+
+

Warning

+

If the master password is disabled, then the saved passwords will +be encrypted using a key which is derived from information within the +configuration database. Use of a master password ensures that the encryption +key does not need to be stored anywhere, and thus prevents possible access +to server credentials if the configuration database becomes available to an +attacker.

+

It is strongly recommended that you use the master password if you use +the Save Password option.

+
+
    +
  • The master password is not stored anywhere on the physical storage. It is +temporarily stored in the application memory and it does not get saved when +the application is restarted.

  • +
  • You are prompted to enter the master password when pgAdmin server is +restarted.

  • +
+Enter master password +
    +
  • If you forget the master password, you can use the Reset Master Password +button to reset the password.

  • +
+Reset master password +
+

Warning

+

Resetting the master password will also remove all saved passwords +and close all existing established connections.

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/materialized_view_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/materialized_view_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..3609299ced6286df24395e47e779c7d8310a8fe5 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/materialized_view_dialog.html @@ -0,0 +1,262 @@ + + + + + + + + + + Materialized View Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Materialized View Dialog

+

Use the Materialized View dialog to define a materialized view. A materialized +view is a stored or cached view that contains the result set of a query. Use +the REFRESH MATERIALIZED VIEW command to update the content of a materialized +view.

+

The Materialized View dialog organizes the development of a materialized_view +through the following dialog tabs: General, Definition, Storage, +Parameter, and Security. The SQL tab displays the SQL code generated by +dialog selections.

+Materialized view dialog general tab +

Use the fields in the General tab to identify the materialized view:

+
    +
  • Use the Name field to add a descriptive name for the materialized view. The +name will be displayed in the pgAdmin tree control.

  • +
  • Use the drop-down listbox next to Owner to select the role that will own +the materialized view.

  • +
  • Select the name of the schema in which the materialized view will reside from +the drop-down listbox in the Schema field.

  • +
  • Store notes about the materialized view in the Comment field.

  • +
+

Click the Definition tab to continue.

+Materialized view dialog storage tab +

Use the fields in the Storage tab to maintain the materialized view:

+
    +
  • Move the With Data switch to the Yes position to specify the materialized +view should be populated at creation time. If not, the materialized view +cannot be queried until you invoke REFRESH MATERIALIZED VIEW.

  • +
  • Use the drop-down listbox next to Tablespace to select a location for the +materialized view.

  • +
  • Use the drop-down list box next to Access Method to specify the table access method to use to store the contents +for the new materialized view; the method needs to be an access method of type TABLE. This field is optional. +This option is available from v12 and above.

  • +
  • Use the Fill Factor field to specify a fill factor for the materialized +view. The fill factor for a table is a percentage between 10 and 100. 100 +(complete packing) is the default.

  • +
+

Click the Code tab to continue.

+Materialized view dialog definition tab +

Use the text editor field in the Code tab to provide the query that will +populate the materialized view. Please note that updating the definition of existing +materialized view would result in loss of Parameter(Table, Toast), Security(Privileges & Security labels), +Indexes and other dependent objects.

+

Click the Parameter tab to continue.

+Materialized view dialog parameter tab +

Use the tabs nested inside the Parameter tab to specify VACUUM and ANALYZE +thresholds; use the Table tab and the Toast Table tab to customize values +for the table and the associated toast table. To change the default values:

+
    +
  • Move the Custom auto-vacuum? switch to the Yes position to perform custom +maintenance on the materialized view and to select values in the +Vacuum table. The Vacuum Table provides default values for maintenance +operations.

  • +
  • Changing Autovacuum enabled? to Not set will reset autovacuum_enabled.

  • +
+

Click the Security tab to continue.

+Materialized view dialog security tab +

Use the Security tab to assign privileges and define security labels.

+

Use the Privileges panel to assign privileges to a role. Click the Add icon +(+) to set privileges for the materialized view:

+
    +
  • Select the name of the role from the drop-down listbox in the Grantee field.

  • +
  • Click inside the Privileges field. Check the boxes to the left of one or +more privileges to grant the selected privilege to the specified user.

  • +
  • The current user, who is the default grantor for granting the privilege, is displayed in the Grantor field.

  • +
+

Click the Add icon (+) to assign additional privileges; to discard a +privilege, click the trash icon to the left of the row and confirm deletion in +the Delete Row popup.

+

Use the Security Labels panel to define security labels applied to the +materialized view. Click the Add icon (+) to add each security label +selection:

+
    +
  • Specify a security label provider in the Provider field. The named provider +must be loaded and must consent to the proposed labeling operation.

  • +
  • Specify a a security label in the Security Label field. The meaning of a +given label is at the discretion of the label provider. PostgreSQL places no +restrictions on whether or how a label provider must interpret security +labels; it merely provides a mechanism for storing them.

  • +
+

Click the Add icon (+) to assign additional security labels; to discard a +security label, click the trash icon to the left of the row and confirm deletion +in the Delete Row popup.

+

Click the SQL tab to continue.

+

Your entries in the Materialized View dialog generate a SQL command (see an +example below). Use the SQL tab for review; revisit or switch tabs to make any +changes to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Materialized View dialog:

+Materialized view dialog sql tab +

The example shown creates a query named new_hires that stores the result of +the displayed query in the pg_default tablespace.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/menu_bar.html b/pgsql/pgAdmin 4/docs/en_US/html/menu_bar.html new file mode 100644 index 0000000000000000000000000000000000000000..cf9764806c9f4f725467873c81b248b69cef79bf --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/menu_bar.html @@ -0,0 +1,377 @@ + + + + + + + + + + Menu Bar — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ + + + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/mfa.html b/pgsql/pgAdmin 4/docs/en_US/html/mfa.html new file mode 100644 index 0000000000000000000000000000000000000000..17722ad18c638f89208e54b0728ca8544c248ed3 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/mfa.html @@ -0,0 +1,216 @@ + + + + + + + + + + Enabling two-factor authentication (2FA) — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Enabling two-factor authentication (2FA)

+
+

About two-factor authentication

+

Two-factor authentication (2FA) is an extra layer of security used when logging +into websites or apps. With 2FA, you have to log in with your username and +password and provide another form of authentication that only you know or have +access to.

+
+
+

Setup two-factor authentication

+

To set up 2FA for pgAdmin 4, you must configure the Two-factor Authentication +settings in config_local.py or config_system.py (see the +config.py documentation) on the system where pgAdmin is +installed in Server mode. You can copy these settings from config.py file and +modify the values for the following parameters.

+ ++++ + + + + + + + + + + + + + + + + + + + +

Parameter

Description

MFA_ENABLED

The default value for this parameter is True. +To disable 2FA, set the value to False

SUPPORTED_MFA_LIST

Set the authentication methods to be supported

MFA_EMAIL_SUBJECT

<APP_NAME> - Verification Code e.g. pgAdmin 4 - +Verification Code

MFA_FORCE_REGISTRATION

Force the user to configure the authentication +method on login (if no authentication is already configured).

+

NOTE: You must set the ‘Mail server settings’ in config_local.py or +config_system.py in order to use ‘email’ as two-factor authentication method +(see the config.py documentation).

+
+
+

Configure two-factor authentication

+

To configure 2FA for a user, you must click on ‘Two-factor Authentication’ +in the User menu in right-top corner. It will list down all the supported +multi factor authentication methods. Click on ‘Setup’ of one of those methods +and follow the steps for each authentication method. You will see the Delete +button for the authentication method, which is already been configured. +Clicking on Delete button will deregister the authentication method for the +current user.

+Configure two-factor authentication +

You can also force users to configure the two-factor +authentication methods on login by setting MFA_FORCE_REGISTRATION parameter +to True.

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/modifying_tables.html b/pgsql/pgAdmin 4/docs/en_US/html/modifying_tables.html new file mode 100644 index 0000000000000000000000000000000000000000..ed32f56bf6b1f2e72aede9fa1ebce2e8e0abf166 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/modifying_tables.html @@ -0,0 +1,157 @@ + + + + + + + + + + Creating or Modifying a Table — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Creating or Modifying a Table

+

pgAdmin 4 provides dialogs that allow you to modify all table properties and +attributes.

+

To access a dialog that allows you to create a database object, right-click on +the object type in the pgAdmin tree control, and select the Create option for +that object. For example, to create a new table, Select a database from the tree control, select the schema under the database, right-click on the Tables +node, and select Create Table…

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/oauth2.html b/pgsql/pgAdmin 4/docs/en_US/html/oauth2.html new file mode 100644 index 0000000000000000000000000000000000000000..89bb8b0c581e15a9c1cad5a22e3ddd35f5f6693a --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/oauth2.html @@ -0,0 +1,268 @@ + + + + + + + + + + Enabling OAUTH2 Authentication — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Enabling OAUTH2 Authentication

+

To enable OAUTH2 authentication for pgAdmin, you must configure the OAUTH2 +settings in the config_local.py or config_system.py file (see the +config.py documentation) on the system where pgAdmin is +installed in Server mode. You can copy these settings from config.py file +and modify the values for the following parameters:

+ ++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Parameter

Description

AUTHENTICATION_SOURCES

The default value for this parameter is internal. +To enable OAUTH2 authentication, you must include oauth2 in the list of values +for this parameter. you can modify the value as follows:

+
    +
  • [‘oauth2’, ‘internal’]: pgAdmin will display an additional button for authenticating with oauth2

  • +
+

OAUTH2_NAME

The name of the Oauth2 provider, ex: Google, Github

OAUTH2_DISPLAY_NAME

Oauth2 display name in pgAdmin

OAUTH2_CLIENT_ID

Oauth2 Client ID

OAUTH2_CLIENT_SECRET

Oauth2 Client Secret

OAUTH2_TOKEN_URL

Oauth2 Access Token endpoint

OAUTH2_AUTHORIZATION_URL

Endpoint for user authorization

OAUTH2_SERVER_METADATA_URL

Server metadata url for your OAuth2 provider

OAUTH2_API_BASE_URL

Oauth2 base URL endpoint to make requests simple, ex: https://api.github.com/

OAUTH2_USERINFO_ENDPOINT

User Endpoint, ex: user (for github) and useinfo (for google)

OAUTH2_SCOPE

Oauth scope, ex: ‘openid email profile’. Note that an ‘email’ claim is required in the resulting profile.

OAUTH2_ICON

The Font-awesome icon to be placed on the oauth2 button, ex: fa-github

OAUTH2_BUTTON_COLOR

Oauth2 button color

OAUTH2_USERNAME_CLAIM

+
The claim which is used for the username. If the value is empty

the email is used as username, but if a value is provided, the claim has to exist. Ex: oid (for AzureAD)

+
+
+

OAUTH2_AUTO_CREATE_USER

+
Set the value to True if you want to automatically

create a pgAdmin user corresponding to a successfully authenticated Oauth2 user. +Please note that password is not stored in the pgAdmin database.

+
+
+

OAUTH2_ADDITIONAL_CLAIMS

+
If a dictionary is provided, pgAdmin will check for a matching key and value on the userinfo endpoint

and in the Id Token. In case there is no match with the provided config, the user will receive an authorization error. +Useful for checking AzureAD wids or groups, GitLab owner, maintainer and reporter claims.

+
+
+

OAUTH2_SSL_CERT_VERIFICATION

+
Set this variable to False to disable SSL certificate verification for OAuth2 provider.

This may need to set False, in case of self-signed certificates.

+
+
+
+
+

Redirect URL

+

The redirect url to configure Oauth2 server is <http/https>://<pgAdmin Server URL>/oauth2/authorize +After successful application authorization, the authorization server will redirect the user back to the pgAdmin url +specified here. Select https scheme if your pgAdmin server serves over https protocol otherwise select http.

+
+
+

Master Password

+

In the multi user mode, pgAdmin uses user’s login password to encrypt/decrypt the PostgreSQL server password. +In the Oauth2 authentication, the pgAdmin does not store the user’s password, so we need an encryption key to store +the PostgreSQL server password. +To accomplish this, set the configuration parameter MASTER_PASSWORD to True, so upon setting the master password, +it will be used as an encryption key while storing the password. If it is False, the server password can not be stored.

+
+
+

Login Page

+

After configuration, on restart, you can see the login page with the Oauth2 login button(s).

+Oauth2 login +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/objects.inv b/pgsql/pgAdmin 4/docs/en_US/html/objects.inv new file mode 100644 index 0000000000000000000000000000000000000000..e7546abd36facdb22517df9e19f767206ae804a6 Binary files /dev/null and b/pgsql/pgAdmin 4/docs/en_US/html/objects.inv differ diff --git a/pgsql/pgAdmin 4/docs/en_US/html/package_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/package_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..50fd508a6109dbfc2a1623f16eeb99461c940d10 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/package_dialog.html @@ -0,0 +1,196 @@ + + + + + + + + + + Package Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Package Dialog

+

Use the Package dialog to create a (user-defined) package specification.

+

The Package dialog organizes the management of a package through the following +dialog tabs: General, Header, Body, and Security. The SQL tab displays the SQL +code generated by dialog selections.

+Package dialog general tab +

Use the fields in the General tab to identify the package:

+
    +
  • Use the Name field to add a descriptive name for the package. The name of a +new package must not match any existing package in the same schema.

  • +
  • Select the schema in which the package will reside from the drop-down listbox +in the Schema field.

  • +
  • Store notes about the package in the Comment field.

  • +
+

Click the Header tab to continue.

+Package dialog header tab +

Use the Header field to define the public interface for the package.

+

Click the Body tab to continue.

+Package dialog body tab +

Use the Body field to provide the code that implements each package object.

+

Click the Security tab to continue.

+Package dialog security tab +

Use the fields in the Security tab to assign EXECUTE privileges for the +package to a role. Click the Add icon (+) to set privileges for the package:

+
    +
  • Select the name of the role from the drop-down listbox in the Grantee field.

  • +
  • Click inside the Privileges field. Check the boxes to the left of a +privilege to grant the selected privilege to the specified user.

  • +
  • The current user, who is the default grantor for granting the privilege, is displayed in the Grantor field.

  • +
+

Click the Add icon (+) to assign additional privileges; to discard a +privilege, click the trash icon to the left of the row, and confirm the deletion +in the Delete Row popup.

+

Click the SQL tab to continue.

+

Your entries in the Package dialog generate a SQL command that creates or +modifies a package definition:

+Package dialog sql tab +

The example shown demonstrates creating a package named empinfo that includes +two function and two procedure.

+
    +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to delete any changes to the dialog.

  • +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/pgagent.html b/pgsql/pgAdmin 4/docs/en_US/html/pgagent.html new file mode 100644 index 0000000000000000000000000000000000000000..a679ace5396babd502b8dabf272c5930dd8f7901 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/pgagent.html @@ -0,0 +1,145 @@ + + + + + + + + + + pgAgent — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

pgAgent

+

pgAgent is a job scheduling agent for Postgres databases, capable of running +multi-step batch or shell scripts and SQL tasks on complex schedules.

+

pgAgent is distributed independently of pgAdmin. You can download pgAgent from +the download area of the pgAdmin website.

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/pgagent_install.html b/pgsql/pgAdmin 4/docs/en_US/html/pgagent_install.html new file mode 100644 index 0000000000000000000000000000000000000000..d67f47eeb1ef0b7f24b2adaafbf3f4697e677433 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/pgagent_install.html @@ -0,0 +1,241 @@ + + + + + + + + + + Installing pgAgent — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Installing pgAgent

+

pgAgent runs as a daemon on Unix systems, and a service on Windows systems. In +most cases it will run on the database server itself - for this reason, pgAgent +is not automatically configured when pgAdmin is installed. In some cases +however, it may be preferable to run pgAgent on multiple systems, against the +same database; individual jobs may be targeted at a particular host, or left +for execution by any host. Locking prevents execution of the same instance of a +job by multiple hosts.

+
+

Database setup

+

Before using pgAdmin to manage pgAgent, you must create the pgAgent extension in +the maintenance database registered with pgAdmin. To install pgAgent on a +PostgreSQL host, connect to the postgres database, and navigate through the +Tools menu to open the Query tool. For server versions 9.1 or later, and +pgAgent 3.4.0 or later, enter the following command in the query window, and +click the Execute icon:

+
CREATE EXTENSION pgagent;
+
+
+

This command will create a number of tables and other objects in a schema +called ‘pgagent’.

+

The database must also have the pl/pgsql procedural language installed - use +the PostgreSQL CREATE LANGUAGE command to install pl/pgsql if necessary. To +install pl/pgsql, enter the following command in the query window, and click +the Execute icon:

+
CREATE LANGUAGE plpgsql;
+
+
+
+
+

Daemon installation on Unix

+
+

Note

+

pgAgent is available in Debian/Ubuntu (DEB) and Redhat/Fedora (RPM) +packages for Linux users, as well as source code. See the +pgAdmin Website. for more +information.

+
+

To install the pgAgent daemon on a Unix system, you will normally need to have +root privileges to modify the system startup scripts. Modifying system startup +scripts is quite system-specific so you should consult your system documentation +for further information.

+

The program itself takes few command line options, most of which are only +needed for debugging or specialised configurations:

+
Usage:
+  /path/to/pgagent [options] <connect-string>
+
+options:
+  -f run in the foreground (do not detach from the terminal)
+  -t <poll time interval in seconds (default 10)>
+  -r <retry period after connection abort in seconds (>=10, default 30)>
+  -s <log file (messages are logged to STDOUT if not specified)>
+  -l <logging verbosity (ERROR=0, WARNING=1, DEBUG=2, default 0)>
+
+
+

The connection string is a standard PostgreSQL libpq connection string (see +the PostgreSQL documentation on the connection string +for further details). For example, the following command line will run pgAgent +against a server listening on the localhost, using a database called ‘pgadmin’, +connecting as the user ‘postgres’:

+
/path/to/pgagent hostaddr=127.0.0.1 dbname=postgres user=postgres
+
+
+
+
+

Service installation on Windows

+
+

Note

+

pgAgent is available in a pre-built installer if you use +EnterpriseDB’s PostgreSQL Installers. +Use the StackBuilder application to download and install it. If installed +in this way, the service will automatically be created and the instructions +below can be ignored.

+
+

pgAgent can install itself as a service on Windows systems. The command line +options available are similar to those on Unix systems, but include an +additional parameter to tell the service what to do:

+
Usage:
+  pgAgent REMOVE <serviceName>
+  pgAgent INSTALL <serviceName> [options] <connect-string>
+  pgAgent DEBUG [options] <connect-string>
+
+  options:
+    -u <user or DOMAIN\user>
+    -p <password>
+    -d <displayname>
+    -t <poll time interval in seconds (default 10)>
+    -r <retry period after connection abort in seconds (>=10, default 30)>
+    -l <logging verbosity (ERROR=0, WARNING=1, DEBUG=2, default 0)>
+
+
+

The service may be quite simply installed from the command line as follows +(adjust the path as required):

+
"C:\Program Files\pgAgent\bin\pgAgent" INSTALL pgAgent -u postgres -p secret hostaddr=127.0.0.1 dbname=postgres user=postgres
+
+
+

You can then start the service at the command line using net start pgAgent, +or from the Services control panel applet. Any logging output or errors will +be reported in the Application event log. The DEBUG mode may be used to run +pgAgent from a command prompt. When run this way, log messages will output to +the command window.

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/pgagent_jobs.html b/pgsql/pgAdmin 4/docs/en_US/html/pgagent_jobs.html new file mode 100644 index 0000000000000000000000000000000000000000..75aab3d1dc391424d3aecf06e06b1573008463d5 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/pgagent_jobs.html @@ -0,0 +1,293 @@ + + + + + + + + + + Creating a pgAgent Job — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Creating a pgAgent Job

+

pgAgent is a scheduling agent that runs and manages jobs; each job consists of +steps and schedules.

+

To create or manage a job, use the pgAdmin tree control to browse to the server +on which the pgAgent database objects were created. The tree control will +display a pgAgent Jobs node, under which currently defined jobs are displayed. +To add a new job, right click on the pgAgent Jobs node, and select Create +pgAgent Job… from the context menu.

+

When the pgAgent dialog opens, use the tabs on the pgAgent Job dialog to +define the steps and schedule that make up a pgAgent job.

+pgAgent dialog general tab +

Use the fields on the General tab to provide general information about a job:

+
    +
  • Provide a name for the job in the Name field.

  • +
  • Move the Enabled switch to the Yes position to enable a job, or No to +disable a job.

  • +
  • Use the Job Class drop-down to select a class (for job categorization).

  • +
  • Use the Host Agent field to specify the name of a machine that is running +pgAgent to indicate that only that machine may execute the job. Leave the +field blank to specify that any machine may perform the job.

    +
    +

    Note

    +

    It is not always obvious what value to specify for the Host Agent +in order to target a job step to a specific machine. With pgAgent running +on the required machines and connected to the scheduler database, you can +use the following query to view the hostnames as reported by each agent:

    +
    SELECT jagstation FROM pgagent.pga_jobagent
    +
    +
    +

    Use the hostname exactly as reported by the query in the Host Agent +field.

    +
    +
  • +
  • Use the Comment field to store notes about the job.

  • +
+pgAgent dialog steps tab +

Use the Steps tab to define and manage the steps that the job will perform. +Click the Add icon (+) to add a new step; then click the compose icon (located +at the left side of the header) to open the step definition dialog:

+pgAgent dialog definition tab +

Use fields on the step definition dialog to define the step:

+
    +
  • Provide a name for the step in the Name field; please note that steps will +be performed in alphanumeric order by name.

  • +
  • Use the Enabled switch to include the step when executing the job (True) +or to disable the step (False).

  • +
  • Use the Kind switch to indicate if the job step invokes SQL code (SQL) +or a batch script (Batch).

    +
      +
    • If you select SQL, use the Code tab to provide SQL code for the step.

    • +
    • If you select Batch, use the Code tab to provide the batch script that +will be executed during the step.

    • +
    +
  • +
+
+

Note

+

The fields Connection type, Database and Connection string are only +applicable when SQL is selected because Batch cannot be run on remote servers.

+
+
    +
  • Use the Connection type switch to indicate if the step is performed on a +local server (Local) or on a remote host (Remote). If you specify a +remote connection should be used for the step, the Connection string field +will be enabled, and you must provide a libpq-style connection string.

  • +
  • Use the Database drop-down to select the database on which the job step +will be performed.

  • +
  • Use the Connection string field to specify a libpq-style connection string +to the remote server on which the step will be performed. For more information +about writing a connection string, please see the +PostgreSQL documentation.

  • +
  • Use the On error drop-down to specify the behavior of pgAgent if it +encounters an error while executing the step. Select from:

    +
      +
    • Fail - Stop the job if you encounter an error while processing this step.

    • +
    • Success - Mark the step as completing successfully, and continue.

    • +
    • Ignore - Ignore the error, and continue.

    • +
    +
  • +
  • Use the Comment field to provide a comment about the step.

  • +
+pgAgent dialog step definition code tab +

Use the context-sensitive field on the step definition dialog’s Code tab to +provide the SQL code or batch script that will be executed during the step:

+
    +
  • If the step invokes SQL code, provide one or more SQL statements in the SQL +query field.

  • +
  • If the step performs a batch script, provide the script in the Script field. +If you are running on a Windows server, standard batch file syntax must be +used. When running on a Linux server, any shell script may be used, provided +that a suitable interpreter is specified on the first line (e.g. #!/bin/sh).

  • +
+

When you’ve provided all of the information required by the step, click the +compose icon to close the step definition dialog. Click the add icon (+) to +add each additional step, or select the Schedules tab to define the job +schedule.

+pgAgent dialog schedules tab +

Click the Add icon (+) to add a schedule for the job; then click the compose +icon (located at the left side of the header) to open the schedule definition +dialog:

+pgAgent dialog schedules definition tab +

Use the fields on the schedule definition tab to specify the days and times at +which the job will execute.

+
    +
  • Provide a name for the schedule in the Name field.

  • +
  • Use the Enabled switch to indicate that pgAgent should use the schedule +(Yes) or to disable the schedule (No).

  • +
  • Use the calendar selector in the Start field to specify the starting date +and time for the schedule.

  • +
  • Use the calendar selector in the End field to specify the ending date and +time for the schedule.

  • +
  • Use the Comment field to provide a comment about the schedule.

  • +
+

Select the Repeat tab to define the days on which the schedule will execute.

+pgAgent dialog schedule repeat tab +

Use the fields on the Repeat tab to specify the details about the schedule in +a cron-style format. The job will execute on each date or time element selected +on the Repeat tab.

+

Click within a field to open a list of valid values for that field; click on a +specific value to add that value to the list of selected values for the field. +To clear the values from a field, click the X located at the right-side of the +field.

+

Use the fields within the Days box to specify the days on which the job will +execute:

+
    +
  • Use the Week Days field to select the days on which the job will execute.

  • +
  • Use the Month Days field to select the numeric days on which the job will +execute. Specify the Last Day to indicate that the job should be performed +on the last day of the month, irregardless of the date.

  • +
  • Use the Months field to select the months in which the job will execute.

  • +
+

Use the fields within the Times box to specify the times at which the job will +execute:

+
    +
  • Use the Hours field to select the hour at which the job will execute.

  • +
  • Use the Minutes field to select the minute at which the job will execute.

  • +
+

Select the Exceptions tab to specify any days on which the schedule will not +execute.

+pgAgent dialog schedule exceptions tab +

Use the fields on the Exceptions tab to specify days on which you wish the job +to not execute; for example, you may wish for jobs to not execute on national +holidays.

+

Click the Add icon (+) to add a row to the exception table, then:

+
    +
  • Click within the Date column to open a calendar selector, and select a date +on which the job will not execute. Specify <Any> in the Date column to +indicate that the job should not execute on any day at the time selected.

  • +
  • Click within the Time column to open a time selector, and specify a time on +which the job will not execute. Specify <Any> in the Time column to +indicate that the job should not execute at any time on the day selected.

  • +
+

When you’ve finished defining the schedule, you can use the SQL tab to review +the code that will create or modify your job.

+pgAgent dialog sql tab +

Click the Save button to save the job definition, or Close to exit the job +without saving. Use the Reset button to remove your unsaved entries from the +dialog.

+

After saving a job, the job will be listed under the pgAgent Jobs node of the +pgAdmin tree control of the server on which it was defined. The Properties +tab in the main pgAdmin window will display a high-level overview of the +selected job, and the Statistics tab will show the details of each run of the +job.

+pgAgent object properties +

To modify an existing job or to review detailed information about a job, +right-click on a job name, and select Properties from the context menu.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/preferences.html b/pgsql/pgAdmin 4/docs/en_US/html/preferences.html new file mode 100644 index 0000000000000000000000000000000000000000..6d7353763615b2816ecafec27243e9682321a432 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/preferences.html @@ -0,0 +1,629 @@ + + + + + + + + + + Preferences Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Preferences Dialog

+

Use options on the Preferences dialog to customize the behavior of the client. +To open the Preferences dialog, select Preferences from the File menu. +The left pane of the Preferences dialog displays a tree control; each node of +the tree control provides access to options that are related to the node under +which they are displayed.

+
    +
  • Use the plus sign (+) to the left of a node name to expand a segment of the +tree control.

  • +
  • Use the minus sign (-) to the left of a node name to close that node.

  • +
+
+

The Browser Node

+

Use preferences found in the Browser node of the tree control to personalize +your workspace.

+Preferences dialog browser display options +

Use the fields on the Display panel to specify general display preferences:

+
    +
  • When the Auto-expand sole children switch is set to True, child nodes will +be automatically expanded if a treeview node is expanded and has only a single +child.

  • +
  • Use the Object explorer state saving interval field to set the treeview state +saving interval. A value of -1 will disable the treeview state saving +functionality.

  • +
  • When the Confirm before closing properties with unsaved changes switch is set to True, +pgAdmin will warn you before closing the properties dialog of an object if there +are any unsaved changes. On user confirmation, the properties dialog will close.

  • +
  • When the Confirm on close or refresh switch is set to True, pgAdmin will +attempt to catch browser close or refresh events and prompt before allowing +them to continue.

  • +
  • When the Hide shared servers? switch is set to True, the client will hide +all the shared servers from the object explorer.

  • +
  • When the Show empty object collections? switch is turned off, then all object +collections which are empty will be hidden from browser tree.

  • +
  • When the Show system objects? switch is set to True, the client will +display system objects such as system schemas (for example, pg_temp) or +system columns (for example, xmin or ctid) in the tree control.

  • +
  • When the Show template databases? switch is set to True, the client will +display template databases.

  • +
+

Use the fields on the Keyboard shortcuts panel to configure shortcuts for the +main window navigation:

+Preferences dialog browser keyboard shortcuts section +
    +
  • The panel displays a list of keyboard shortcuts available for the main window; +select the combination of the modifier keys along with the key to configure +each shortcut.

  • +
+

Use the fields on the Nodes panel to select the object types that will be +displayed in the Browser tree control:

+Preferences dialog browser nodes section +
    +
  • The panel displays a list of database objects; slide the switch located next +to each object to Show or Hide the database object. When querying system +catalogs, you can reduce the number of object types displayed to increase +speed.

  • +
+

Use the fields on the Object Breadcrumbs panel to change object breadcrumbs +related settings:

+Preferences dialog object breadcrumbs section +
    +
  • Use Enable object breadcrumbs? to enable or disable object breadcrumbs +displayed on on object mouse hover.

  • +
  • Use Show comment with object breadcrumbs? to enable or disable the +comment visibility which comes displayed with object breadcrumbs.

  • +
+

Use the fields on the Processes panel to change processes tab +related settings:

+Preferences dialog processes section +
    +
  • Change Process details/logs retention days to the number of days, +the process info and logs will be automatically cleared.

  • +
+

Use fields on the Properties panel to specify browser properties:

+Preferences dialog browser properties section +
    +
  • Include a value in the Count rows if estimated less than field to perform a +SELECT count(*) if the estimated number of rows in a table (as read from the +table statistics) is below the specified limit. After performing the SELECT +count(*), pgAdmin will display the row count. The default is 2000.

  • +
  • Provide a value in the Maximum job history rows field to limit the number of +rows to show on the statistics tab for pgAgent jobs. The default is 250.

  • +
+

Use field on Tab settings panel to specify the tab related properties.

+Preferences dialog browser properties section +
    +
  • Use Debugger tab title placeholder field to customize the Debugger tab title.

  • +
  • When the Dynamic tab size If set to True, the tabs will take full size as per the title, it will also applicable for already opened tabs

  • +
  • When the Open in new browser tab filed is selected for Query tool, Schema Diff or Debugger, it will +open in a new browser tab when invoked.

  • +
  • Use the Query tool tab title placeholder field to customize the query tool tab title.

  • +
  • Use View/Edit tab title placeholder field to customize the View/Edit Data tab title.

  • +
+
+
+

The Dashboards Node

+

Expand the Dashboards node to specify your dashboard display preferences.

+Preferences dialog dashboard display options +
    +
  • Set the warning and alert threshold value to highlight the long-running +queries on the dashboard.

  • +
  • When the Show activity? switch is set to True, activity tables will be +displayed on dashboards.

  • +
  • When the Show graphs? switch is set to True, graphs will be displayed on +dashboards.

  • +
+Preferences dialog dashboard refresh options +

Use the fields on the Refresh rates panel to specify your refersh rates +preferences for the graphs on the Dashboard tab:

+
    +
  • Use the Block I/O statistics refresh rate field to specify the number of +seconds between block I/O statistic samples displayed in graphs.

  • +
  • Use the Session statistics refresh rate field to specify the number of +seconds between session statistic samples displayed in graphs.

  • +
  • Use the Transaction throughput refresh rate field to specify the number of +seconds between transaction throughput samples displayed in graphs.

  • +
  • Use the Tuples in refresh rate field to specify the number of seconds +between tuples-in samples displayed in graphs.

  • +
  • Use the Tuples out refresh rate field to specify the number of seconds +between tuples-out samples displayed in graphs.

  • +
+
+
+

The Debugger Node

+

Expand the Debugger node to specify your debugger display preferences.

+

Use the fields on the Keyboard shortcuts panel to configure shortcuts for the +debugger window navigation:

+Preferences dialog debugger keyboard shortcuts section +
+
+

The ERD Tool Node

+

Expand the ERD Tool node to specify your ERD Tool display preferences.

+

Use the fields on the Keyboard shortcuts panel to configure shortcuts for the +ERD Tool window navigation:

+Preferences dialog erd keyboard shortcuts section +

Use the fields on the Options panel to manage ERD preferences.

+Preferences dialog erd options section +
    +
  • When the SQL With DROP Table switch is set to True, the SQL +generated by the ERD Tool will add DROP table DDL before each CREATE +table DDL.

  • +
  • Table Relation Depth is useful when generating an ERD for a table. +It allows to set the limit on the depth level pgAdmin should traverse +to find the relations. Use -1 to set no limit.

  • +
+
+
+

The Graphs Node

+

Expand the Graphs node to specify your Graphs display preferences.

+Preferences dialog dashboard graph options +
    +
  • Use the Chart line width field to specify the width of the lines on the +line chart.

  • +
  • When the Show graph data points? switch is set to True, data points will +be visible on graph lines.

  • +
  • When the Show mouse hover tooltip? switch is set to True, a tooltip will +appear on mouse hover on the graph lines giving the data point details.

  • +
  • When the Use different data point styles? switch is set to True, +data points will be visible in a different style on each graph lines.

  • +
+
+
+

The Miscellaneous Node

+

Expand the Miscellaneous node to specify miscellaneous display preferences.

+Preferences dialog user language section +
    +
  • Use the User language drop-down listbox to select the display language for +the client.

  • +
+Preferences dialog themes section +
    +
  • Use the Themes drop-down listbox to select the theme for pgAdmin. You’ll also get a preview just below the +drop down. Note that, to apply the theme you need to refresh the pgAdmin page. You can also submit your +own themes, check here how. +Currently we support Standard, Dark and High Contrast theme.

  • +
+
+
+

The Paths Node

+

Expand the Paths node to specify the locations of supporting utility and help +files.

+Preferences dialog binary path section +

Use the fields on the Binary paths panel to specify the path to the directory +that contains the utility programs (pg_dump, pg_dumpall, pg_restore and psql) for +monitored databases:

+
    +
  • Use the EDB Advanced Server Binary Path grid to specify the location of the +EDB Postgres Advanced Server utility programs based on the server version. +If the respective path is not set, then pgAdmin will pick up the path for which +‘Set as default’ is checked else pgAdmin will attempt to find the utilities in +standard locations used by EnterpriseDB.

  • +
  • Use the PostgreSQL Binary Path grid to specify the location of the +PostgreSQL utility programs based on the server version. If the respective +path is not set, then pgAdmin will pick up the path for which ‘Set as default’ +is checked else pgAdmin will attempt to find the utilities in standard +locations used by PostgreSQL.

  • +
+

Note: Use the ‘Validate path’ button to check the existence of the utility +programs (pg_dump, pg_dumpall, pg_restore and psql) and there respective versions.

+Preferences dialog binary path help section +

Use the fields on the Help panel to specify the location of help files.

+
    +
  • Use the EDB Advanced Server Help Path to specify the path to EDB Postgres +Advanced Server documentation.

  • +
  • Use the PostgreSQL Help Path to specify the path to PostgreSQL +documentation.

  • +
+

Please note: the default help paths include the VERSION placeholder; the +$VERSION$ placeholder will be replaced by the current database version.

+
+
+

The Query Tool Node

+

Expand the Query Tool node to access panels that allow you to specify your +preferences for the Query Editor tool.

+Preferences dialog sqleditor auto completion option +

Use the fields on the Auto Completion panel to set the auto completion options.

+
    +
  • When the Autocomplete on key press switch is set to True then autocomplete +will be available on key press along with CTRL/CMD + Space. If it is set to +False then autocomplete is only activated when CTRL/CMD + Space is pressed.

  • +
  • When the Keywords in uppercase switch is set to True then keywords are +shown in upper case.

  • +
+Preferences dialog sqleditor csv output option +

Use the fields on the CSV/TXT Output panel to control the CSV/TXT output.

+
    +
  • Use the CSV field separator drop-down listbox to specify the separator +character that will be used in CSV/TXT output.

  • +
  • Use the CSV quote character drop-down listbox to specify the quote character +that will be used in CSV/TXT output.

  • +
  • Use the CSV quoting drop-down listbox to select the fields that will be +quoted in the CSV/TXT output; select Strings, All, or None.

  • +
  • Use the Replace null values with option to replace null values with +specified string in the output file. Default is set to ‘NULL’.

  • +
+Preferences dialog sqleditor display options +

Use the fields on the Display panel to specify your preferences for the Query +Tool display.

+
    +
  • When the Connection status switch is set to True, each new instance of the +Query Tool will display connection and transaction status.

  • +
  • Use the Connection status refresh rate field to specify the number of +seconds between connection/transaction status updates.

  • +
  • Use the Query info notifier timeout field to control the behaviour of the +notifier that is displayed when query execution completes. A value of -1 +will disable the notifier, and a value of 0 will display it until clicked. If +a positive value above zero is specified, the notifier will be displayed for +the specified number of seconds. The default is 5.

  • +
+Preferences dialog sqleditor editor settings +

Use the fields on the Editor panel to change settings of the query editor.

+
    +
  • When the Brace matching? switch is set to True, the editor will highlight +pairs of matched braces.

  • +
  • When the Code folding? switch is set to False, the editor will disable +code folding. Disabling will improve editor performance with large files.

  • +
  • Use the Font size field to specify the font size that will be used in text +boxes and editors.

  • +
  • When the Insert bracket pairs? switch is set to True, the editor will +automatically insert paired brackets.

  • +
  • When the Line wrapping switch is set to True, the editor will implement +line-wrapping behavior.

  • +
  • When the Plain text mode? switch is set to True, the editor mode will be +changed to text/plain. Keyword highlighting and code folding will be disabled. +This will improve editor performance with large files.

  • +
+Preferences dialog sqleditor explain options +

Use the fields on the Explain panel to specify the level of detail included in +a graphical EXPLAIN.

+
    +
  • When the Show buffers? switch is set to True, graphical explain details +will include information about buffer usage.

  • +
  • When the Show costs? switch is set to True, graphical explain details will +include information about the estimated startup and total cost of each plan, +as well as the estimated number of rows and the estimated width of each row.

  • +
  • When the Show settings? switch is set to True, graphical explain details +will include the information on the configuration parameters.

  • +
  • When the Show summary? switch is set to True, graphical explain details +will include the summary information about the query plan.

  • +
  • When the Show timing? switch is set to True, graphical explain details +will include the startup time and time spent in each node in the output.

  • +
  • When the Show wal? switch is set to True, graphical explain details +will include the information on WAL record generation.

  • +
  • When the Verbose output? switch is set to True, graphical explain details +will include extended information about the query execution plan.

  • +
+Preferences dialog sqleditor graph visualiser section +

Use the fields on the Graph Visualiser panel to specify the settings +related to graphs.

+
    +
  • Use the Row Limit field to specify the maximum number of rows that will +be plotted on a chart.

  • +
+Preferences dialog sqleditor options section +

Use the fields on the Options panel to manage editor preferences.

+
    +
  • When the Auto commit? switch is set to True, each successful query is +committed after execution.

  • +
  • When the Auto rollback on error? switch is set to True, failed queries are rolled +back.

  • +
  • When the Copy SQL from main window to query tool? switch is set to True, +the CREATE sql of the selected object will be copied to query tool when query tool +will open.

  • +
  • When the Prompt to save unsaved data changes? switch is set to True, the +editor will prompt the user to saved unsaved data when exiting the data +editor.

  • +
  • When the Prompt to save unsaved query changes? switch is set to True, the +editor will prompt the user to saved unsaved query modifications when exiting +the Query Tool.

  • +
  • When the Prompt to commit/rollback active transactions? switch is set to +True, the editor will prompt the user to commit or rollback changes when +exiting the Query Tool while the current transaction is not committed.

  • +
  • When the Sort View Data results by primary key columns? If set to True, +data returned when using the View/Edit Data - All Rows option will be sorted +by the Primary Key columns by default. When using the First/Last 100 Rows options, +data is always sorted.

  • +
+Preferences dialog sql results grid section +

Use the fields on the Results grid panel to specify your formatting +preferences for copied data.

+
    +
  • When the Columns sized by is set to Column data, then data columns will +auto-size to the maximum width of the data in the column as loaded in the +first batch. If set to Column name, the column will be sized to the widest +of the data type or column name.

  • +
  • Specify the maximum width of the column in pixels when ‘Columns sized by’ is +set to Column data. If ‘Columns sized by’ is set to Column name then this +setting won’t have any effect.

  • +
  • Specify the number of records to fetch in one batch in query tool when +query result set is large. Changing this value will override +ON_DEMAND_ROW_COUNT setting from config file.

  • +
  • Use the Result copy field separator drop-down listbox to select the field +separator for copied data.

  • +
  • Use the Result copy quote character drop-down listbox to select the quote +character for copied data.

  • +
  • Use the Result copy quoting drop-down listbox to select which type of fields +require quoting; select All, None, or Strings.

  • +
+Preferences dialog sql keyboard shortcuts section +

Use the fields on the Keyboard shortcuts panel to configure shortcuts for the +Query Tool window navigation:

+Preferences dialog SQL Formatting section +

Use the fields on the SQL formatting panel to specify your preferences for +reformatting of SQL.

+
    +
  • Use the Data type case option to specify whether to change data types +into upper, lower, or preserve case.

  • +
  • Use the Expression width option to specify maximum number of characters +in parenthesized expressions to be kept on single line.

  • +
  • Use the Function case option to specify whether to change function +names into upper, lower, or preserve case.

  • +
  • Use the Identifier case option to specify whether to change identifiers +(object names) into upper, lower, or capitalized case.

  • +
  • Use the Keyword case option to specify whether to change keywords into +upper, lower, or preserve case.

  • +
  • Use Lines between queries to specify how many empty lines to leave +between SQL statements. If set to zero it puts no new line.

  • +
  • Use Logical operator new line to specify newline placement before or +after logical operators (AND, OR, XOR).

  • +
  • Use New line before semicolon? to specify whether to place query +separator (;) on a separate line.

  • +
  • Use the Spaces around operators? option to specify whether or not to include +spaces on either side of operators.

  • +
  • Use the Tab size option to specify the number of spaces per tab or indent.

  • +
  • Use the Use spaces? option to select whether to use spaces or tabs when +indenting.

  • +
+
+
+

The Schema Diff Node

+

Expand the Schema Diff node to specify your display preferences.

+Preferences schema diff +

Use the Ignore Grant/Revoke switch to ignores the grant and revoke command while comparing the objects.

+

Use the Ignore Owner switch to ignores the owner while comparing the objects.

+

Use the Ignore Tablespace switch to ignores the tablespace while comparing the objects.

+

Use the Ignore Whitespace switch to ignores the whitespace while comparing +the string objects. Whitespace includes space, tabs, and CRLF.

+
+
+

The Storage Node

+

Expand the Storage node to specify your storage preferences.

+Preferences dialog storage section +

Use the fields on the Options panel to specify storage preferences.

+
    +
  • Use the File dialog view drop-down listbox to select the style of icons and +display format that will be displayed when you open the file manager; select +List to display a list view, or Grid to display folder icons.

  • +
  • Use the Last directory visited field to specify the name of the folder in +which the file manager will open.

  • +
  • Use the Maximum file upload size(MB) field on the Options panel of the +Storage node to specify the maximum file size for an upload.

  • +
  • When the Show hidden files and folders? switch is set to True, the file +manager will display hidden files and folders.

  • +
+
+

Using ‘setup.py’ command line script

+
+

Note

+

To manage preferences using setup.py script, you must use +the Python interpreter that is normally used to run pgAdmin to ensure +that the required Python packages are available. In most packages, this +can be found in the Python Virtual Environment that can be found in the +installation directory. When using platform-native packages, the system +installation of Python may be the one used by pgAdmin.

+
+
+
+
+

Manage Preferences

+
+
+

Get Preferences

+

To get all the preferences listed, invoke setup.py with get-prefs command line option. +You can also get this mapping by hovering the individual preference in the Preference UI dialog.

+
/path/to/python /path/to/setup.py get-prefs
+
+
+
+
+

Save Preferences

+

To save the preferences, invoke setup.py with set-prefs command line option, followed by username, +preference_key=value and auth_source. Multiple preference can be given too by a space separated. +If auth_source is not given, Internal authentication will be consider by default.

+
/path/to/python /path/to/setup.py set-prefs user1@gmail.com sqleditor:editor:comma_first=true
+
+# To specify multiple preferences options
+/path/to/python /path/to/setup.py set-prefs user1@gmail.com sqleditor:editor:comma_first=true sqleditor:keyboard_shortcuts:toggle_case=true
+
+# to specify an auth_source
+/path/to/python /path/to/setup.py set-prefs user1@gmail.com sqleditor:editor:comma_first=true --auth-source=ldap
+
+
+
+
+

Updating Preferences preferences.json

+

To update preferences defined in json file, simply run setup.py `` with ``set-prefs command followed by username +and JSON file containing the preferences.

+
/path/to/python /path/to/setup.py set-prefs user1@gmail.com --input-file /Users/yogeshmahajan/Desktop/pref.json
+
+
+
+
+

JSON format

+

The JSON file simply contains preference_key=value. Preference key value mapping can be obtained by hovering the +individual preference in the Preference UI dialog.

+

The following is an typical example for preferences.json :

+
{
+    "preferences":
+        {
+            "browser:display:show_system_objects":  true,
+            "browser:display:show_user_defined_templates": true,
+            "browser:display:confirm_on_refresh_close": false,
+            "misc:themes:theme": "dark",
+
+        }
+}
+
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/primary_key_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/primary_key_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..7f8033d3178194af7126cdb644d65e0d28670e2a --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/primary_key_dialog.html @@ -0,0 +1,205 @@ + + + + + + + + + + Primary key Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Primary key Dialog

+

Use the Primary key dialog to create or modify a primary key constraint. A +primary key constraint indicates that a column, or group of columns, uniquely +identifies rows in a table. This requires that the values in the selected +column(s) be both unique and not null.

+

The Primary key dialog organizes the development of a primary key constraint +through the General and Definition tabs. The SQL tab displays the SQL code +generated by dialog selections.

+Primary key dialog general tab +

Use the fields in the General tab to identify the primary key:

+
    +
  • Use the Name field to add a descriptive name for the primary key constraint. +The name will be displayed in the pgAdmin tree control.

  • +
+

Click the Definition tab to continue.

+Primary key dialog definition tab +

Use the fields in the Definition tab to define the primary key constraint:

+
    +
  • Click inside the Columns field and select one or more column names from the +drop-down listbox. To delete a selection, click the x to the left of the +column name. The primary key constraint should be different from any unique +constraint defined for the same table; the selected column(s) for the +constraints must be distinct.

  • +
  • Use Include columns field to specify columns for INCLUDE clause of the +index. This option is available in Postgres 11 and later.

  • +
  • Select the name of the tablespace in which the primary key constraint will +reside from the drop-down listbox in the Tablespace field.

  • +
  • Select the name of an index from the drop-down listbox in the Index field. +This field is optional. Adding a primary key will automatically create a +unique B-tree index on the column or group of columns listed in the primary +key, and will force the column(s) to be marked NOT NULL.

  • +
  • Use the Fill Factor field to specify a fill factor for the table and index. +The fill factor for a table is a percentage between 10 and 100. 100 (complete +packing) is the default.

  • +
  • Move the Deferrable? switch to the Yes position to specify the timing of +the constraint is deferrable and can be postponed until the end of the +statement. The default is No.

  • +
  • If enabled, move the Deferred? switch to the Yes position to specify the +timing of the constraint is deferred to the end of the statement. The default +is No.

  • +
+

Click the SQL tab to continue.

+

Your entries in the Primary key dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by user selections in +the Primary key dialog:

+Primary key dialog sql tab +

The example shown demonstrates creating a primary key constraint named +jobhist_pk on the empno column of the jobhist table.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/procedure_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/procedure_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..084bef773e0174a2634a6e4e37edecd253cd926f --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/procedure_dialog.html @@ -0,0 +1,294 @@ + + + + + + + + + + Procedure Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Procedure Dialog

+

Use the Procedure dialog to create a procedure; procedures are supported by +PostgreSQL v11+ and EDB Postgres Advanced Server. The Procedure dialog allows +you to implement options of the CREATE PROCEDURE command.

+

The Procedure dialog organizes the development of a procedure through the +following dialog tabs: General, Definition, Code, Options, Arguments, +Parameters, and Security. The SQL tab displays the SQL code generated by +dialog selections.

+Procedure dialog general tab +

Use the fields in the General tab to identify a procedure:

+
    +
  • Use the Name field to add a descriptive name for the procedure. The name +will be displayed in the pgAdmin tree control.

  • +
  • Use the drop-down listbox next to Owner to select a role.

  • +
  • Select the name of the schema in which the procedure will reside from the +drop-down listbox in the Schema field.

  • +
  • Store notes about the procedure in the Comment field.

  • +
+

Click the Definition tab to continue.

+Procedure dialog definition tab +

Use the fields in the Definition tab to define the procedure:

+
    +
  • Use the drop-down listbox next to Language to select a language. The default +is edbspl.

  • +
  • Use the fields in the Arguments section to define an argument. Click Add to set +parameters and values for the argument:

  • +
  • Use the drop-down listbox next to Data type to select a data type.

  • +
  • Use the drop-down listbox next to Mode to select a mode. Select IN for an +input parameter; select OUT for an output parameter; select INOUT for both +an input and an output parameter; or, select VARIADIC to specify a VARIADIC +parameter.

  • +
  • Write a name for the argument in the Argument Name field.

  • +
  • Specify a default value for the argument in the Default Value field.

  • +
+

Click Add to define another argument; to discard an argument, click the trash +icon to the left of the row and confirm deletion in the Delete Row popup.

+

Click the Code tab to continue.

+Procedure dialog code tab +
    +
  • Use the Code field to specify the code that will execute when the procedure +is called.

  • +
+

Click the Options tab to continue.

+Procedure dialog options tab +

Use the fields in the Options tab to describe or modify the behavior of the +procedure:

+
    +
  • Use the drop-down listbox under Volatility to select one of the following. +VOLATILE is the default value.

    +
    +
      +
    • VOLATILE indicates that the value can change even within a single table +scan, so no optimizations can be made.

    • +
    • STABLE indicates that the procedure cannot modify the database, and that +within a single table scan it will consistently return the same result for +the same argument values, but that its result could change across SQL +statements.

    • +
    • IMMUTABLE indicates that the procedure cannot modify the database and +always returns the same result when given the same argument values.

    • +
    +
    +
  • +
  • Move the Strict? switch to indicate if the procedure always returns NULL +whenever any of its arguments are NULL. If Yes, the procedure is not +executed when there are NULL arguments; instead a NULL result is assumed +automatically. The default is No.

  • +
  • Move the Security of definer? switch to specify that the procedure is to be +executed with the privileges of the user that created it. The default is No.

  • +
  • Use the Estimated cost field to specify a positive number representing the +estimated execution cost for the procedure, in units of cpu_operator_cost. If +the procedure returns a set, this is the cost per returned row.

  • +
  • Move the Leak proof? switch to indicate whether the procedure has side +effects — it reveals no information about its arguments other than by its +return value. The default is No.

  • +
+

Click the Parameters tab to continue.

+Procedure dialog parameters tab +

Use the fields in the Parameters tab to specify settings that will be applied +when the procedure is invoked:

+
    +
  • Use the drop-down listbox next to Parameter Name in the Parameters panel +to select a parameter.

  • +
  • Click the Add button to add the variable to Name field in the table.

  • +
  • Use the Value field to specify the value that will be associated with the +selected variable. This field is context-sensitive.

  • +
+

Click the Security tab to continue.

+Procedure dialog security tab +

Use the Security tab to assign privileges and define security labels.

+

Use the Privileges panel to assign execute privileges for the procedure to a +role:

+
    +
  • Select the name of the role from the drop-down listbox in the Grantee field.

  • +
  • Click inside the Privileges field. Check the boxes to the left of one or +more privileges to grant the selected privilege to the specified user.

  • +
  • The current user, who is the default grantor for granting the privilege, is displayed in the Grantor field.

  • +
+

Click Add to assign additional privileges; to discard a privilege, click the +trash icon to the left of the row and confirm deletion in the Delete Row +popup.

+

Use the Security Labels panel to define security labels applied to the +procedure. Click Add to add each security label selection:

+
    +
  • Specify a security label provider in the Provider field. The named provider +must be loaded and must consent to the proposed labeling operation.

  • +
  • Specify a a security label in the Security Label field. The meaning of a +given label is at the discretion of the label provider. PostgreSQL places no +restrictions on whether or how a label provider must interpret security +labels; it merely provides a mechanism for storing them.

  • +
+

Click Add to assign additional security labels; to discard a security label, +click the trash icon to the left of the row and confirm deletion in the Delete +Row popup.

+

Click the SQL tab to continue.

+

Your entries in the Procedure dialog generate a SQL command (see an example +below). Use the SQL tab for review; revisit or switch tabs to make any changes +to the SQL command.

+
+

Example

+

The following is an example of the sql command generated by selections made in +the Procedure dialog:

+Procedure dialog sql tab +

The example demonstrates creating a procedure that returns a list of employees +from a table named emp. The procedure is a SECURITY DEFINER, and will execute +with the privileges of the role that defined the procedure.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore configuration parameters.

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/processes.html b/pgsql/pgAdmin 4/docs/en_US/html/processes.html new file mode 100644 index 0000000000000000000000000000000000000000..229cb9deb90da5e9774d8c95a4c74b11e5fe6cf9 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/processes.html @@ -0,0 +1,175 @@ + + + + + + + + + + Processes — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Processes

+

There are certain tasks which pgAdmin runs in the background. The processes +running in the background can be viewed in the processes tab. It shows the +process details of Backup, Restore, Maintenance, Import/Export and Cloud instance +creation.

+Processes Tab +

The columns of the processes table shows:

+
    +
  • The PID of the forked OS process.

  • +
  • The Type of the task being performed.

  • +
  • The Server name for which the task is.

  • +
  • The Object can be a database, table, mview or anything which gives more info.

  • +
  • The Start Time of the process, sorted descending by default.

  • +
  • The current Status of the process. It can be Running, Finished, Failed, Terminated.

  • +
  • The Time Taken to complete. It will keep updating if it is running.

  • +
+

There are two action buttons on each row:

+
    +
  • The Stop Process button allows you to kill a running process.

  • +
  • The More details button allows you to open the process watcher which shows the +process logs and other details.

  • +
+

You can also select the checkboxes and click on Delete and Acknowledge button +on the top to clear the process info and logs.

+
+

Process Watcher

+Process Watcher +

The Process Watcher logs all the activity associated with the process/task and provides +additional information for troubleshooting +Use the Stop Process button to stop the Backup process.

+
+

Note

+

If you are running pgAdmin in Server Mode you can click on the sm_icon icon in the process watcher window to open the file location in the Storage Manager. You can use the Storage Manager to download the backup file on the client machine .

+
+
+
+

Watch the demo

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/psql_tool.html b/pgsql/pgAdmin 4/docs/en_US/html/psql_tool.html new file mode 100644 index 0000000000000000000000000000000000000000..492272cc8664b62dfff20716b78551b23867e9b9 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/psql_tool.html @@ -0,0 +1,149 @@ + + + + + + + + + + PSQL Tool — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

PSQL Tool

+

The PSQL tool allows users to connect to PostgreSQL or EDB Advanced server using +the psql command line interface through their browser.

+
    +
  • Open the PSQL tool from the Tools or object explorer context menu, or use PSQL +tool button at the top of the object explorer.

  • +
  • PSQL will connect to the current connected database from the object explorer.

  • +
+PSQL tool window +

You can open multiple instances of the PSQL tool in individual tabs simultaneously. +To close the PSQL tool, click the X in the upper-right hand corner of the tab bar.

+

Note: On the Windows platform, this feature is available on Windows 10 (1809 +version), and Windows Server 2019 and onwards.

+

Note: The PSQL tool is always available when pgAdmin is running in Desktop +mode, but is disabled by default in Server mode. This is because users can run +arbitrary shell commands through psql which may be considered a security risk in +some deployments. System Administrators can enable the use of the PSQL tool in +the pgAdmin configuration by setting the ENABLE_PSQL option to True; see +The config.py File for more information.

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/publication_dialog.html b/pgsql/pgAdmin 4/docs/en_US/html/publication_dialog.html new file mode 100644 index 0000000000000000000000000000000000000000..917afecac896b3342f7e5db2396a780fb60b3690 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/publication_dialog.html @@ -0,0 +1,198 @@ + + + + + + + + + + Publication Dialog — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Publication Dialog

+

Logical replication uses a publish and subscribe model with one or more subscribers subscribing to one or more publications on a publisher node.

+

Use the publication dialog to create a publication. A publication is a set of changes generated from a table or a group of tables or a schema or a group of schemas, and might also be described as a change set or replication set.

+

The publication dialog organizes the development of a publication through the following dialog tabs: General, Tables and Options. The SQL tab displays the SQL code generated by dialog selections.

+Publication dialog general tab +

Use the fields in the General tab to identify the publication:

+
    +
  • Use the Name field to add a descriptive name for the publication. The name will be displayed in the pgAdmin tree control.

  • +
  • The Owner field takes the name of the user automatically as current connected user. You can change the owner after creating publication using alter publication.

  • +
+

Click the Tables tab to continue.

+

Tables tab for PostgreSQL version <= 14

+Publication dialog definition tab +

Tables tab for PostgreSQL version >= 15

+Publication dialog definition tab +

Use the Tables tab to set table properties for the publication:

+
    +
  • Move the switch next to All tables? to Yes to replicate all the tables of the database, including tables created in the future.

  • +
  • Move the switch next to Only table? to Yes to replicate only the listed tables excluding all its descendant tables.

  • +
  • Specify a table or list of tables separated by a comma in Tables field to replicate all the listed table. With PostgreSQL 15 forward, specify a table or list of tables to replicate all the listed tables along with specific columns and/or WHERE clause to filter rows.

  • +
  • With PostgreSQL 15 forward, specify a schema or list of schemas separated by a comma in Tables In Schema field to replicate all the listed schemas. This field will be disabled if any columns are selected for tables.

  • +
+

Click the Options tab to continue.

+Publication dialog options tab +

Use the Options tab to set option properties for the publication:

+
    +
  • Use the With section to determine which DML operations will be published by the new publication to the subscribers. Move the switch next to INSERT, UPDATE, DELETE, or TRUNCATE to No if you do not want to replicate any of these DML operations from Publication to Subscription. By default, all the switches are set to Yes allowing all the DML operations.

  • +
+
+

Note

+

A published table must have a “replica identity” configured in order to be able to replicate UPDATE and DELETE operations. You can change with ALTER TABLE statement. For more information on replica identity see Logical Replication Publication.

+
+

Click the SQL tab to continue.

+

Your entries in the Publication dialog generate a SQL command (see an example below). Use the SQL tab for review; revisit or switch tabs to make any changes to the SQL command.

+

Example

+

The following is an example of the sql command generated by user selections in +the Publication dialog:

+Publication dialog sql tab +

The example creates a publication named pub1 that is owned by postgres. It +allows replication of all the DML operations.

+
    +
  • Click the Info button (i) to access online help.

  • +
  • Click the Save button to save work.

  • +
  • Click the Close button to exit without saving work.

  • +
  • Click the Reset button to restore all the default settings.

  • +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/query_tool.html b/pgsql/pgAdmin 4/docs/en_US/html/query_tool.html new file mode 100644 index 0000000000000000000000000000000000000000..41161f137d47e2c7db98bc8bf7565d1738d53223 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/query_tool.html @@ -0,0 +1,505 @@ + + + + + + + + + + Query Tool — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Query Tool

+

The Query Tool is a powerful, feature-rich environment that allows you to +execute arbitrary SQL commands and review the result set. You can access the +Query Tool via the Query Tool menu option on the Tools menu, or through the +context menu of select nodes of the Object explorer control. The Query Tool +allows you to:

+
    +
  • Issue ad-hoc SQL queries.

  • +
  • Execute arbitrary SQL commands.

  • +
  • Edit the result set of a SELECT query if it is +updatable.

  • +
  • Displays current connection and transaction status as configured by the user.

  • +
  • Save the data displayed in the output panel to a CSV file.

  • +
  • Review the execution plan of a SQL statement in either a text, a graphical +format or a table format (similar to https://explain.depesz.com).

  • +
  • View analytical information about a SQL statement.

  • +
+Query tool window +

You can open multiple copies of the Query tool in individual tabs +simultaneously. To close a copy of the Query tool, click the X in the +upper-right hand corner of the tab bar.

+

The Query Tool features two panels:

+
    +
  • The upper panel displays the SQL Editor. You can use the panel to enter, +edit, or execute a query. It also shows the History tab which can be used +to view the queries that have been executed in the session, and a Scratch Pad +which can be used to hold text snippets during editing. If the Scratch Pad is +closed, it can be re-opened (or additional ones opened) by right-clicking in +the SQL Editor and other panels and adding a new panel.

  • +
  • The lower panel displays the Data Output panel. The tabbed panel displays +the result set returned by a query, information about a query’s execution plan, +server messages related to the query’s execution and any asynchronous +notifications received from the server.

  • +
+
+

Toolbar

+

The toolbar is described in the following subsections.

+ +
+
+

The SQL Editor Panel

+

The SQL editor panel is a workspace where you can manually provide a query, +copy a query from another source, or read a query from a file. The SQL editor +features syntax coloring and autocompletion.

+Query tool editor +

To use autocomplete, begin typing your query; when you would like the Query +editor to suggest object names or commands that might be next in your query, +press the Control+Space key combination. For example, type “SELECT * FROM” +(without quotes, but with a trailing space), and then press the Control+Space +key combination to select from a popup menu of autocomplete options.

+Query tool autocomplete feature +

After entering a query, select the Execute script icon from the toolbar. The +complete contents of the SQL editor panel will be sent to the database server +for execution. To execute only a section of the code that is displayed in the +SQL editor, highlight the text that you want the server to execute, and click +the Execute script icon.

+Query tool execute query section +

The message returned by the server when a command executes is displayed on the +Messages tab. If the command is successful, the Messages tab displays +execution details.

+Query tool message panel +

Options on the Edit menu offer functionality that helps with code formatting +and commenting:

+
    +
  • The auto-indent feature will automatically indent text to the same depth as +the previous line when you press the Return key.

  • +
  • Block indent text by selecting two or more lines and pressing the Tab key.

  • +
  • Implement or remove SQL style or toggle C style comment notation within your +code.

  • +
+

You can also drag and drop certain objects from the treeview which +can save time in typing long object names. Text containing the object name will be +fully qualified with schema. Double quotes will be added if required. +For functions and procedures, the function name along with parameter names will +be pasted in the Query Tool.

+
+
+

Query History Panel

+

Use the Query History tab to review activity for the current session:

+Query tool history panel +

The Query History tab displays information about recent commands:

+
    +
  • The date and time that a query was invoked.

  • +
  • The text of the query.

  • +
  • The number of rows returned by the query.

  • +
  • The amount of time it took the server to process the query and return a +result set.

  • +
  • Messages returned by the server (not noted on the Messages tab).

  • +
  • The source of the query (indicated by icons corresponding to the toolbar).

  • +
+

You can show or hide the queries generated internally by pgAdmin (during +‘View/Edit Data’ or ‘Save Data’ operations).

+

You can remove a single query by selecting it and clicking on the Remove +button. If you would like to remove all of the histories from the +Query History tab, then click on the Remove All button.

+

By using the Copy button, you can copy a particular query to the clipboard, +and with the Copy to Query Editor button, you can copy a specific query to +the Query Editor tab. During this operation, all existing content in the +Query Editor is erased.

+

Query History is maintained across sessions for each database on a per-user +basis when running in Query Tool mode. In View/Edit Data mode, history is not +retained. By default, the last 20 queries are stored for each database. This +can be adjusted in config_local.py or config_system.py (see the +config.py documentation) by overriding the +MAX_QUERY_HIST_STORED value. See the Deployment section +for more information.

+
+
+

The Data Output Panel

+

The Data Output panel displays data and statistics generated by the most +recently executed query.

+Query tool output panel +

The Data Output tab displays the result set of the query in a table format. +You can:

+
    +
  • Select and copy from the displayed result set.

  • +
  • Use the Execute script options to retrieve query execution information and +set query execution options.

  • +
  • Use the Save results to file icon to save the content of the Data Output +tab as a comma-delimited file.

  • +
  • Edit the data in the result set of a SELECT query if it is updatable.

  • +
+

A result set is updatable if:

+
    +
  • All columns are either selected directly from a single table, or +are not table columns at all (e.g. concatenation of 2 columns). +Only columns that are selected directly from the table are +editable, other columns are read-only.

  • +
  • All the primary key columns or OIDs of the table are selected in the +result set.

  • +
+

Any columns that are renamed or selected more than once are also read-only.

+

Editable and read-only columns are identified using pencil and lock icons +(respectively) in the column headers.

+Query tool editable and read-only columns +

The psycopg2 driver version should be equal to or above 2.8 for updatable +query result sets to work.

+

An updatable result set is identical to the Data Grid in +View/Edit Data mode, and can be modified in the same way.

+

If Auto-commit is off, the data changes are made as part of the ongoing +transaction, if no transaction is ongoing a new one is initiated. The data +changes are not committed to the database unless the transaction is committed.

+

If any errors occur during saving (for example, trying to save NULL into a +column with NOT NULL constraint) the data changes are rolled back to an +automatically created SAVEPOINT to ensure any previously executed queries in +the ongoing transaction are not rolled back.

+

All rowsets from previous queries or commands that are displayed in the Data +Output panel will be discarded when you invoke another query; open another +Query Tool tab to keep your previous results available.

+
+
+

Explain Panel

+

To generate the Explain or Explain Analyze plan of a query, click on +Explain or Explain Analyze button in the toolbar.

+

More options related to Explain and Explain Analyze can be selected from +the drop down on the right side of Explain Analyze button in the toolbar.

+Query tool toolbar explain button +

Please note that pgAdmin generates the Explain [Analyze] plan in JSON format.

+

On successful generation of Explain plan, it will create three tabs/panels +under the Explain panel.

+
    +
  • Graphical

  • +
+

Please note that EXPLAIN VERBOSE cannot be displayed graphically. Click on +a node icon on the Graphical tab to review information about that item; a popup +window will display on the right side with the information about the selected +object. For information on JIT statistics, triggers and a summary, click on the +button on top-right corner; a similar popup window will be displayed when appropriate.

+

Use the download button on top left corner of the Explain canvas to download +the plan as an SVG file.

+

Note: Download as SVG is not supported on Internet Explorer.

+Query tool graphical explain plan +

Note that the query plan that accompanies the Explain analyze is available on +the Data Output tab.

+
    +
  • Table

  • +
+

Table tab shows the plan details in table format, it generates table format +similar to explain.depesz.com. Each row of the table represent the data for a +Explain Plan Node. It may contain the node information, exclusive timing, +inclusive timing, actual vs planned rows differences, actual rows, planned +rows, loops.

+

background color of the exclusive, inclusive, and Rows X columns may vary based on the +difference between actual vs planned.

+

If percentage of the exclusive/inclusive timings of the total query time is: +> 90 - Red color +> 50 - Orange (between red and yellow) color +> 10 - Yellow color

+

If planner mis-estimated number of rows (actual vs planned) by +10 times - Yellow color +100 times - Orange (between Red and Yellow) color +1000 times - Red color

+Query tool explain plan table +
    +
  • Statistics

  • +
+

Statistics tab shows two tables: +1. Statistics per Plan Node Type +2. Statistics per Table

+Query tool explain plan statistics +
+
+

Messages Panel

+

Use the Messages tab to view information about the most recently executed +query:

+Query tool output messages +

If the server returns an error, the error message will be displayed on the +Messages tab, and the syntax that caused the error will be underlined in the +SQL editor. If a query succeeds, the Messages tab displays how long the +query took to complete and how many rows were retrieved:

+Query tool output information +
+
+

Notifications Panel

+

Use the Notifications tab to view the notifications using PostgreSQL Listen/ +Notify feature. For more details see PostgreSQL documentation.

+

Example:

+
    +
  1. Execute LISTEN “foo” in first Query Tool session

  2. +
+Query tool notifications listen +

2. In the another Query Tool session, execute Notify command or pg_notify +function to send the notification of the event together with the payload.

+Query tool notifications notify +

3. You can observe the Notification tab in the first Query Tool session +where it shows the Recorded time, Event, Process ID, and the Payload of the +particular channel.

+Query tool notifications panel +
+
+

Graph Visualiser Panel

+

Click the Graph Visualiser button in the toolbar to generate the Graphs of +the query results. The graph visualiser supports Line Charts, Stacked Line Charts, +Bar Charts, Stacked Bar Charts, and Pie Charts.

+Query tool graph visualiser panel +
    +
  • Graph Type

  • +
+

Choose the type of the graph that you would like to generate.

+Query tool graph visualiser graph type +
    +
  • X Axis

  • +
+

Choose the column whose value you wish to display on X-axis from the X Axis +dropdown. Select the <Row Number> option to use the number of rows as labels +on the X-axis.

+Query tool graph visualiser xaxis +
    +
  • Y Axis

  • +
+

Choose the columns whose value you wish to display on Y-axis from the Y Axis +dropdown. Users can choose multiple columns. Choose the <Select All> option +from the drop-down menu to select all the columns.

+Query tool graph visualiser yaxis +
    +
  • Download and Zoom button

  • +
+

Zooming is performed by clicking and selecting an area over the chart with the +mouse. The Zoom to original button will bring you back to the original zoom +level.

+

Click the Download button on the button bar to download the chart.

+Query tool graph visualiser toolbar +
+

Line Chart

+

The Line Chart can be generated by selecting the ‘Line Chart’ +from the Graph Type drop-down, selecting the X-axis and the Y-axis, and +clicking on the ‘Generate’ button. Below is an example of a chart of employee +names and their salaries.

+Query tool graph visualiser line chart +

Set Use different data point styles? option to true in the Preferences Dialog, +to show data points in a different style on each graph lines.

+
+
+

Stacked Line Chart

+

The Stacked Line Chart can be generated by selecting the ‘Stacked Line Chart’ +from the Graph Type drop-down, selecting the X-axis and the Y-axis, and +clicking on the ‘Generate’ button.

+Query tool graph visualiser stacked line chart +
+
+

Bar Chart

+

The Bar Chart can be generated by selecting the ‘Bar Chart’ +from the Graph Type drop-down, selecting the X-axis and the Y-axis, and +clicking on the ‘Generate’ button.

+Query tool graph visualiser bar chart +
+
+

Stacked Bar Chart

+

The Stacked Bar Chart can be generated by selecting the ‘Stacked Bar Chart’ +from the Graph Type drop-down, selecting the X-axis and the Y-axis, and +clicking on the ‘Generate’ button.

+Query tool graph visualiser stacked bar chart +
+
+

Pie Chart

+

The Pie Chart can be generated by selecting the ‘Pie Chart’ +from the Graph Type drop-down, selecting the Label and Value, and +clicking on the ‘Generate’ button.

+Query tool graph visualiser pie chart +
+
+
+

Connection Status

+

Use the Connection status feature to view the current connection and +transaction status by clicking on the status icon in the Query Tool:

+Query tool connection and transaction statuses +
+
+

Change connection

+

User can connect to another server or database from existing open session of query tool.

+
    +
  • Click on the connection link next to connection status.

  • +
  • Now click on the <New Connection> option from the dropdown.

  • +
+Query tool connection options +
    +
  • Now select server, database, user, and role to connect and click on the ‘Save’ button.

  • +
+Query tool connection dialog +
    +
  • A newly created connection will now get listed in the options.

  • +
  • To connect, select the newly created connection from the dropdown list.

  • +
+
+
+

Macros

+

Query Tool Macros enable you to execute pre-defined SQL queries with a single key press. Pre-defined queries can contain the placeholder $SELECTION$. Upon macro execution, the placeholder will be replaced with the currently selected text in the Query Editor pane of the Query Tool.

+Query Tool Manage macros +

To create a macro, select the Manage Macros option from the Macros menu on the Query Tool. Select the key you wish to use, enter the name of the macro, and the query, optionally including the selection placeholder, and then click the Save button to store the macro.

+Query Tool Manage Macros dialogue +

To delete a macro, select the macro on the Manage Macros dialogue, and then click the Delete button. +The server will prompt you for confirmation to delete the macro.

+Query Tool Manage Macros Clear row confirmation +

To execute a macro, simply select the appropriate shortcut keys, or select it from the Macros menu.

+Query Tool Macros Execution +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/query_tool_toolbar.html b/pgsql/pgAdmin 4/docs/en_US/html/query_tool_toolbar.html new file mode 100644 index 0000000000000000000000000000000000000000..641f7a53fc558cae4ad5b6f57f743e121cc06941 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/query_tool_toolbar.html @@ -0,0 +1,443 @@ + + + + + + + + + + Query Tool Toolbar — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Query Tool Toolbar

+

The Query Tool toolbar uses context-sensitive icons that provide shortcuts to +frequently performed tasks. If an icon is highlighted, the option is enabled; +if the icon is grayed-out, the task is disabled.

+
+

Note

+

The Query Tool and +View/Edit Data tools are actually different operating +modes of the same tool. Some controls will be disabled in either mode.

+
+Query tool toolbar +

Hover over an icon in pgAdmin to display a tooltip that describes the icon’s +functionality.

+
+

File Options

+ +++++ + + + + + + + + + + + + + + + + +

Icon

Behavior

Shortcut

Open File

Click the Open File icon to display a previously saved query in the SQL Editor.

Accesskey + O

Save File

Click the Save icon to perform a quick-save of a previously saved query, or to access the +Save menu:

+
+
    +
  • Select Save to save the selected content of the SQL Editor panel in a file.

  • +
  • Select Save As to open a new browser dialog and specify a new location to which to save the +selected content of the SQL Editor panel.

  • +
+
+

Accesskey + S

+
+
+

Filter/Limit Options

+ +++++ + + + + + + + + + + + + + + + + +

Icon

Behavior

Shortcut

Filter

Click the Filter icon to set filtering and sorting criteria for the data when in View/Edit data +mode. Click the down arrow to access other filtering and sorting options:

+
+
    +
  • In the SQL Filter, you can enter a SQL query as filtering criteria. +In Data Sorting, you can select the column and specify the order for sorting.

  • +
  • Click Filter by Selection to show only the rows containing the values in the selected cells.

  • +
  • Click Exclude by Selection to show only the rows that do not contain the values in the +selected cells.

  • +
  • Click Remove Sort/Filter to remove any previously selected sort or filtering options.

  • +
+
+

Accesskey + F

Limit Selector

Select a value in the Limit Selector to limit the size of the dataset to a number of rows.

Accesskey + R

+
+
+

Query Editing Options

+Query tool editing options + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Icon

Behavior

Shortcut

Edit

Use the Edit menu to search, replace, or navigate the code displayed in the SQL Editor:

Select Find to provide a search target, and search the SQL Editor contents.

Cmd+F

Select Replace to locate and replace (with prompting) individual occurrences of the target.

Option+Cmd+F (MAC) +Ctrl+Shift+F (Others)

Select Go to Line/Column to go to specified line number and column position

Cmd+L or Ctrl+L

Select Indent Selection to indent the currently selected text.

Tab

Select Unindent Selection to remove indentation from the currently selected text.

Shift+Tab

Select Toggle Comment to comment/uncomment any lines that contain the selection in SQL style.

Cmd+/

Select Clear Query to clear the query editor window.

Cmd+.

Select Format SQL to format the selected SQL or all the SQL if none is selected

Shift+Cmd+K

+
+
+

Query Execution

+Query tool execute options + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Icon

Behavior

Shortcut

Stop

Click the Stop icon to cancel the execution of the currently running query.

Accesskey + Q

Execute script

Click the Execute script icon to either execute or refresh the query highlighted in the SQL +editor panel. Click the down arrow to access other execution options:

+
+
    +
  • Add a check next to Auto rollback on error? to instruct the server to automatically roll back +a transaction if an error occurs during the transaction.

  • +
  • Add a check next to Auto commit? to instruct the server to automatically commit each +transaction. Any changes made by the transaction will be visible to others, and +durable in the event of a crash.

  • +
+
+

F5

Explain

Click the Explain icon to view an explanation plan for the current query. The result of the +EXPLAIN is displayed graphically on the Explain tab of the output panel, and in text +form on the Data Output tab.

F7

Explain analyze

Click the Explain analyze icon to invoke an EXPLAIN ANALYZE command on the current query.

+

Navigate through the Explain Options menu to select options for the EXPLAIN command:

+
+
    +
  • Select Verbose to display additional information regarding the query plan.

  • +
  • Select Costs to include information on the estimated startup and total cost of each +plan node, as well as the estimated number of rows and the estimated width of each +row.

  • +
  • Select Buffers to include information on buffer usage.

  • +
  • Select Timing to include information about the startup time and the amount of time +spent in each node of the query.

  • +
  • Select Summary to include the summary information about the query plan.

  • +
  • Select Settings to include the information on the configuration parameters.

  • +
  • Select Wal to include the information on WAL record generation.

  • +
+
+

Shift+F7

Commit

Click the Commit icon to commit the transaction.

Shift+CTRL+M

Rollback

Click the Rollback icon to rollback the transaction.

Shift+CTRL+R

Macros

Click the Macros icon to manage the macros. You can create, edit or clear the macros through +the Manage Macros option.

+
+
+

Data Editing Options

+Query tool data editing options + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Icon

Behavior

Shortcut

Add row

Click the Add row icon to add a new row

Copy

Click the Copy icon to copy the content with or without header:

+
+
    +
  • +
    Click the Copy icon to copy the content that is currently highlighted in the Data Output

    panel.

    +
    +
    +
  • +
  • Click Copy with headers to copy the highlighted content along with the header.

  • +
+
+

Accesskey + C

Paste

Click the Paste icon to paste a previously copied row with or without serial/identity values:

+
+
    +
  • Click the Paste icon to paste a previously copied row into a new row.

  • +
  • Click the Paste with SERIAL/IDENTITY values? if you want to paste the copied column values +in the serial/identity columns.

  • +
+
+

Accesskey + P

Delete

Click the Delete icon to mark the selected rows for deletion. These marked rows get deleted +when you click the Save Data Changes icon.

Accesskey + D

Save Data Changes

Click the Save Data Changes icon to save data changes (insert, update, or delete) in the Data +Output Panel to the server.

F6

Save results to +file

Click the Save results to file icon to save the result set of the current query as a delimited +text file (CSV, if the field separator is set to a comma). This button will only be enabled when +a query has been executed and there are results in the data grid. You can specify the CSV/TXT +settings in the Preference Dialogue under SQL Editor -> CSV/TXT output.

F8

Graph Visualiser

Use the Graph Visualiser button to generate graphs of the query results.

+
+
+

Status Bar

+Query tool status bar +

The status bar shows the following information:

+
    +
  • Total rows: The total number of rows returned by the query.

  • +
  • Query complete: The time is taken by the query to complete.

  • +
  • Rows selected: The number of rows selected in the data output panel.

  • +
  • Changes staged: This information showed the number of rows added, deleted, and updated.

  • +
  • Ln: In the Query tab, it is the line number at which the cursor is positioned.

  • +
  • Col: In the Query tab, it is the column number at which the cursor is positioned

  • +
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes.html new file mode 100644 index 0000000000000000000000000000000000000000..c8a722c3f863170eaf87b314a84a509a9e3b0db8 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes.html @@ -0,0 +1,317 @@ + + + + + + + + + + Release Notes — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Release Notes

+

pgAdmin release notes provide information on the features and improvements in +each release. This page includes release notes for major releases and minor +(bugfix) releases. Select your version from the list below to see the release +notes for it.

+ +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_0.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_0.html new file mode 100644 index 0000000000000000000000000000000000000000..f5946802d2118ae843222e0dc990b9a4495a8abc --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_0.html @@ -0,0 +1,231 @@ + + + + + + + + + + Version 1.0 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 1.0

+

Release date: 2016-09-29

+

The first major release of pgAdmin 4. With a more modern look and feel, this +release includes the following features;

+
    +
  • Multiplatform

  • +
  • Designed for multiple PostgreSQL versions and derivatives

  • +
  • Extensive documentation

  • +
  • Multiple deployment models

  • +
  • Tools

  • +
  • Routine maintenance

  • +
  • Create, view and edit all common PostgreSQL objects

  • +
  • Multibyte support

  • +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_1.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_1.html new file mode 100644 index 0000000000000000000000000000000000000000..508236d09cf35127a68b6a1dbb58941f1ab3a2a1 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_1.html @@ -0,0 +1,280 @@ + + + + + + + + + + Version 1.1 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 1.1

+

Release date: 2016-10-27

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 1.0;

+
+

Features

+
+
Issue #1328 - Add Python 3.5 Support
+
Issue #1859 - Include wait information on the activity tab of the dashboards
+
+
+
+

Bug fixes

+
+
Issue #1155 - Display the start value when the user creates sequence
+
Issue #1531 - Fix to update privileges for Views and Materials Views where “string indices must be integers error” displayed
+
Issue #1574 - Display SQL in SQL pane for security label in PG and EPAS server
+
Issue #1576 - Make security label option available in procedure properties
+
Issue #1577 - Make debug option available for package function and procedure
+
Issue #1596 - Correct spelling error from evnt_turncate to evnt_truncate
+
Issue #1599 - Ensure the grant wizard works with objects with special characters in the name
+
Issue #1622 - Fix issue using special characters when creating synonym
+
Issue #1728 - Properties refreshing after objects are edited
+
Issue #1739 - Prevent the user from trying to…..
+
Issue #1785 - Correctly identify server type upon first connection
+
Issue #1786 - Ensure errorModel unset property is set correctly when adding a new server
+
Issue #1808 - Set seconds to valid value in pgAgent job schedule
+
Issue #1817 - Display message “server does not support ssl” if server with ca-cert or ca-full added
+
Issue #1821 - Optionally sign both the Mac app bundle and the disk image
+
Issue #1822 - Handle non-ascii responses from the server when connecting
+
Issue #1823 - Attempt to sign the Windows installer, failing with a warning if there’s no cert available
+
Issue #1824 - Add documenation for pgAgent
+
Issue #1835 - Allow users to choose SELECT permissions for tables and sequences in the grant wizard
+
Issue #1837 - Fix refreshing of FTS dictionaries which was causing error “Connection to the server has been lost”
+
Issue #1838 - Don’t append new objects with the wrong parent in tree browser if the correct one isn’t loaded
+
Issue #1843 - Function definition matches value returned from pg_get_functiondef()
+
Issue #1845 - Allow refreshing synonym node. Does not display message “Unimplemented method (node) for this url (/browser/synonym/nodes/1/7/14301/2200/test)”
+
Issue #1847 - Identify the collation correctly when reverse engineering table SQL. ERROR: schema “default” does not exist no longer displayed
+
Issue #1849 - Remove security keys from config.py/config_local.py
+
Issue #1857 - Fix error while renaming FTS dictionary and FTS template nodes
+
Issue #1858 - Ensure the File Manager honours the file type while traversing the directories.
+
Issue #1861 - Properly generate exclusion constraint SQL.
+
Issue #1863 - Correctly quote type names in reverse engineered SQL for tables
+
Issue #1864 - Fix layout of DateTimePicker control help message.
+
Issue #1867 - Allow package bodies to be dropped.
+
Issue #1868 - Resolved issue where Integer type of preferences are not updated
+
Issue #1872 - Fix the file manager when used under Python 3.
+
Issue #1877 - Ensure preferences values are stored properly.
+
Issue #1878 - Ensure steps and schedules can be created in empty jobs. ProgrammingError: can’t adapt type ‘Undefined’ was displayed
+
Issue #1880 - Add new indexes to the correct parent on the treeview.
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_2.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_2.html new file mode 100644 index 0000000000000000000000000000000000000000..05ce73d2b4519b8fb0d132fc864758a24adb9bc5 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_2.html @@ -0,0 +1,330 @@ + + + + + + + + + + Version 1.2 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 1.2

+

Release date: 2017-02-10

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 1.1.

+
+

Features

+
+
Issue #1375 - Migrate the runtime to QtWebEngine from QtWebKit
+
Issue #1765 - Find and replace functionality with regexp and group replacement
+
Issue #1789 - Column width of data output panel should fit to data (as pgAdmin III)
+
Issue #1790 - [Web] Support setting a field’s value to “null”
+
Issue #1848 - macOS appbundle is missing postgresql binaries for import etc.
+
Issue #1910 - Remember last used directory in the file manager
+
Issue #1911 - Direct path navigation in the file manager
+
Issue #1922 - Improve handling of corrupt configuration databases
+
Issue #1963 - Add a Chinese (Simplified) translation
+
Issue #1964 - Create a docs tarball along with the source tarball
+
Issue #2025 - Allow the SQL Editors to word-wrap
+
Issue #2124 - Create a template loader to simplify SQL template location, and remove duplicate templates
+
+
+
+

Bug fixes

+
+
Issue #1227 - Display improved error message for Debugger listener starting error and reset between executions
+
Issue #1267 - Fix issue where MINIFY_HTML doesn’t work with the docs
+
Issue #1364 - Ensure dialogue control buttons are consistent
+
Issue #1394 - Fix Table dialogue column specification issues
+
Issue #1432 - Enhanced OSX File Browser
+
Issue #1585 - Cannot save scripts to the network
+
Issue #1599 - Ensure the grant wizard works with objects with special characters in the name
+
Issue #1603 - Fix quoting of objects names for external utilities.
+
Issue #1679 - Re-engineer the background process executor to avoid using sqlite as some builds of components it relies on do not support working in forked children
+
Issue #1680 - Render column headers at the correct width in the Query Tool under Firefox
+
Issue #1729 - Improve display of role options
+
Issue #1730 - Improve the display of role membership on both the properties panel and role dialogue
+
Issue #1745 - Ensure breakpoints are cleared properly when working with Debugger
+
Issue #1747 - Add newly created triggers to the treeview
+
Issue #1780 - Properly size the SQL Editor gutter as the width of the line numbers increases
+
Issue #1792 - List files and folders alphabetically
+
Issue #1800 - Handle the template property on databases appropriately
+
Issue #1801 - Handle databases with datallowconn == false
+
Issue #1807 - Properly detect when files have changed in the Query Tool and set flag accordingly
+
Issue #1830 - Fix a SQL error when reverse-engineering ROLE SQL on EPAS servers
+
Issue #1832 - Prevent attempts to access what may be an empty list in Dependancies tab
+
Issue #1840 - Enable/disable NULLs and ASC/DESC options for index columns and exclusion constraints appropriately
+
Issue #1842 - Show index columns in the correct order in RE-SQL
+
Issue #1855 - Ensure dialogue panels show their errors themselves, and not in the properties panel when creating Trigger Function
+
Issue #1865 - Properly schema qualify domains when reverse engineering SQL
+
Issue #1874 - Add file resources to the windows runtime
+
Issue #1893 - Fix refreshing of Unique constraints
+
Issue #1896 - Use the correct OID for retrieving properties of freshly created exclusion constraints
+
Issue #1899 - Properly quote role names when specifying function ownership
+
Issue #1909 - Handle startup errors more gracefully in the runtime
+
Issue #1912 - Properly format arguments passed by triggers to functions
+
Issue #1919 - Ensure all changes to rows are stored in the data editor
+
Issue #1924 - Ensure the check_option is only set when editing views when appropriate
+
Issue #1936 - Don’t strip rn from “Download as CSV” batches of rows, as it leads to malformed data
+
Issue #1937 - Generate mSQL for new schemas correctly
+
Issue #1938 - Fix sorting of numerics in the statistics grids
+
Issue #1939 - Updated dynamic default for the window size (90% x 90%)
+
Issue #1949 - Ensure trigger function names are schema qualified in trigger RE-SQL
+
Issue #1951 - Fix issue where nnable to browse table columns when oid values exceeed max int
+
Issue #1953 - Add display messages and notices received in the Query Tool
+
Issue #1961 - Fix upgrade check on Python 3
+
Issue #1962 - Ensure treeview collection nodes are translated in the UI
+
Issue #1967 - Store layout changes on each adjustment
+
Issue #1976 - Prevent users selecting elements of the UI that shouldn’t be selectable
+
Issue #1979 - Deal with Function arguments correctly in the properties dialogue
+
Issue #1986 - Fix various encoding issues with multibyte paths and filenames resulting in empty file save
+
Issue #1992 - Quote identifiers correctly in auto-complete
+
Issue #1994 - Update to show modifications in edit grid
+
Issue #2000 - Allow setting of effective_io_concurrency on tablespaces in 9.6+
+
Issue #2005 - Fix various mis-spellings of VACUUM
+
Issue #2006 - Fix error when modifying table name or set schema on tables with postgis geometry column
+
Issue #2007 - Correctly sort rows by the pkey when viewing first/last 100
+
Issue #2009 - Reset the column list properly if the access method is changed on an index to ensure error handling works correctly
+
Issue #2012 - Prevent attempts to create server groups with no name
+
Issue #2015 - Enable trigger option when user tries to change Row trigger value through properties section
+
Issue #2024 - Properly handle setting comments and other options on databases with allowconn = False
+
Issue #2026 - Improve detection of the pldbgapi extension and functions before allowing debugging
+
Issue #2027 - Fix inconsistent table styling
+
Issue #2028 - Fix display of double scrollbars on the grant wizard
+
Issue #2032 - Fix time formatting on dashboards
+
Issue #2033 - Show icons for unique and exclusion constraints in the dependency/dependents panels
+
Issue #2045 - Update copyright year on doc page
+
Issue #2046 - Fix error when setting up regression on Windows for pgadmin4
+
Issue #2047 - Ensure dialogues cannot be moved under the navbar
+
Issue #2061 - Enable/disable NULLs and ASC/DESC options for index columns and exclusion constraints appropriately
+
Issue #2065 - Improve display of columns of exclusion contraints and foreign keys in the properties lists
+
Issue #2069 - Correct tablespace displayed in table properties
+
Issue #2076 - Handle sized time/timestamp columns correctly
+
Issue #2109 - Update copyright year
+
Issue #2110 - Handle saved directories that no longer exist gracefully
+
Issue #2112 - Enable comments on Initial database through right Click
+
Issue #2133 - Fix display of graphical query plans for UPDATE/DELETE queries
+
Issue #2138 - Fix display of zeros in read-only grid editors
+
Issue #2139 - Fixed issue causing Message (Connection to the server has been lost.) displayed with Materialized view and view under sql tab
+
Issue #2152 - Fix handling of “char” columns
+
Issue #2156 - Added compatibility fixes for newer versions of Jinja2 (e.g. 2.9.5+)
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_3.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_3.html new file mode 100644 index 0000000000000000000000000000000000000000..e1aa0163a8d666e7effdb34c0b6f39424436d340 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_3.html @@ -0,0 +1,276 @@ + + + + + + + + + + Version 1.3 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 1.3

+

Release date: 2017-03-10

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 1.2.

+
+

Features

+
+
Issue #2036 - Query tool efficiency - SlickGrid result set format efficiency
+
Issue #2038 - Query tool efficiency - Incremental back off when polling
+
Issue #2163 - Make syntax highlighting more visible
+
Issue #2210 - Build a universal Python wheel instead of per-python-version ones
+
Issue #2215 - Improve visibility of syntax highlighting colours
+
+
+
+

Bug fixes

+
+
Issue #1796 - Add missing “Run Now” option for pgAdmin jobs
+
Issue #1797 - Resolve encoding issues with DATA_DIR
+
Issue #1914 - Resolved error utf8’ codec can’t decode byte
+
Issue #1983 - Fix bug in Sql query contains Arabic Charaters
+
Issue #2089 - Add PARALLEL SAFE|UNSAFE|RESTRICTED support
+
Issue #2115 - Fix exclusion constraint reverse engineered SQL
+
Issue #2119 - Fix display of long integers and decimals
+
Issue #2126 - Correct node labels in Preferences for EDB functions and procedures
+
Issue #2151 - Display un-sized varlen column types correctly in the Query Tool
+
Issue #2154 - Fix display of long integers and decimals
+
Issue #2159 - Resolve issue where Query editor is not working with Python2.6
+
Issue #2160 - Various encoding fixes to allow ‘ascii’ codec to decode byte 0xc3 in position 66: ordinal not in range(128)
+
Issue #2166 - Resolved import/Export issue for a table
+
Issue #2173 - Resolved issues where Sequences API test cases are not working in PG9.2 and PPAS9.2
+
Issue #2174 - Resolved various file-system encoding/decoding related cases
+
Issue #2185 - Removed sorting columns on the treeview
+
Issue #2192 - Fix startup complete tests to ensure we properly poll the server for completed startup
+
Issue #2198 - Fix function arguments when generating create SQL
+
Issue #2200 - Properly handle event trigger functions in different schemas
+
Issue #2201 - Fix renaming of check constraints when the table name is changed at the same time
+
Issue #2202 - Fix issue where Dependents query fails due to non ascii characters
+
Issue #2204 - Fixed issue where pgadmin 4 jobs not showing any activity
+
Issue #2205 - Fix display of boolean nulls in the Query Tool
+
Issue #2208 - Ensure primary key column names are quoted in View Data mode of the Query Tool
+
Issue #2212 - Ensure servers are deleted when their parent group is deleted
+
Issue #2213 - Enable right click on browser tree
+
Issue #2218 - Show the correct indeterminate state when editing new boolean values
+
Issue #2228 - Authenticate the runtime to the server
+
Issue #2230 - Prevent the Slonik logo obscuring the login dialogue on small displays in server mode
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_4.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_4.html new file mode 100644 index 0000000000000000000000000000000000000000..85d543997536356b51a307e0585e92f22d725f58 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_4.html @@ -0,0 +1,272 @@ + + + + + + + + + + Version 1.4 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 1.4

+

Release date: 2017-04-13

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 1.3.

+
+

Features

+
+
Issue #2232 - Add the ability to gray-out/disable the “Save Password” option when creating a connection to a server
+
Issue #2261 - Display table DDL for Greenplum in SQL tab
+
Issue #2320 - Added German translation
+
+
+
+

Bug fixes

+
+
Issue #2077 - Add missing “Run Now” option for pgAdmin jobs
+
Issue #2105 - Fix validation on the table dialogue so the Save button isn’t enabled if the name is removed and autovac custom settings are enabled
+
Issue #2145 - Resolve the issue for restoring the table from the backup
+
Issue #2187 - Ensure the web/ directory is cleared before upgrading Windows installations
+
Issue #2190 - Allow users to select UI language at login or from Preferences rather than unpredictable behaviour from browsers
+
Issue #2226 - Show tooltips for disabled buttons to help user learning
+
Issue #2241 - Fix numeric control validation in nested schemas
+
Issue #2243 - Fix dropping of databases with Unicode names
+
Issue #2244 - Prevent an error being displayed if the user views data on a table with no columns
+
Issue #2246 - Add missing braces to reverse engineered SQL header block for Functions
+
Issue #2258 - Fix handling of DATERANGE[] type
+
Issue #2264 - Resolve error message ExtDeprecationWarning displayed on new pgAdmin4 setup for Python 3.4 on ubuntu 14.04 Linux 64
+
Issue #2265 - Resolved import/Export issue for a table
+
Issue #2274 - Properly handle truncated table names
+
Issue #2277 - Resolved various file-system encoding/decoding related cases
+
Issue #2281 - Ensure menus are updated after disconnecting a server
+
Issue #2283 - Check if cell is in multiselect mode before setting default selection of multiple values
+
Issue #2287 - Properly handle EXPLAIN queries entered directly by the user in the Query Tool
+
Issue #2291 - Fix error highlighting in the Query Tool
+
Issue #2299 - Fix usage of QString
+
Issue #2303 - Fix ascending/descending sort order in backgrid while clicking on the headers
+
Issue #2304 - Resolve the issue for restoring the table from the backup
+
Issue #2305 - Resolve the issue where Generic function qtLiteral was not adapting values properly when they contain non ascii characters
+
Issue #2310 - Fix Dialog Help where Query Tool/Debugger opens in new browser tab
+
Issue #2319 - Resolve issue where Click on pgAdmin4 logo leads to unauthorized error
+
Issue #2321 - Improved functionality of browser tree when adding new nodes if parent collection node has not loaded
+
Issue #2330 - Ensure the Query Tool displays but does not render HTML returned by the server in the results grid
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_5.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_5.html new file mode 100644 index 0000000000000000000000000000000000000000..9d57e52cef2957b2ef51591f11044d6c05314691 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_5.html @@ -0,0 +1,264 @@ + + + + + + + + + + Version 1.5 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 1.5

+

Release date: 2017-05-19

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 1.4.

+
+

Features

+
+
Issue #2216 - Allow column or row selection in the Query Tool
+
+
+
+

Bug fixes

+
+
Issue #2225 - Hide menu options for creating objects, if the object type is set to hidden. Includes Jasmine tests
+
Issue #2253 - Fix various issues in CSV file download feature
+
Issue #2257 - Improve handling of nulls and default values in the data editor
+
Issue #2271 - Don’t change the trigger icon back to “enabled” when the trigger is updated when it’s disabled
+
Issue #2284 - Allow creation of tables with pure numeric names
+
Issue #2292 - Only reconnect to databases that were previously connected
+
Issue #2314 - Fix various issues in CSV file download feature
+
Issue #2315 - Fix sorting of sizes on the statistics views by sorting raw values and prettifying on the client side. Includes Jasmine tests for the prettyfying function
+
Issue #2318 - Order foreign table columns correctly
+
Issue #2331 - Fix binary search algorithm so new treeview nodes are added in the correct position
+
Issue #2336 - Update inode info when refreshing treeview nodes.
+
Issue #2339 - Ensure the treeview can be scrolled horizontally
+
Issue #2350 - Fix handling of default parameters ordering in functions
+
Issue #2354 - Fix the Backup module where it was not working if user changes its preference language other than English
+
Issue #2356 - Ensure errors thrown when deleting rows in the Query Tool in edit mode are shown properly
+
Issue #2360 - Fix various issues in CSV file download feature
+
Issue #2369 - Support loading files with Unicode BOMs
+
Issue #2377 - Update psycopg2 version for PostgreSQL 10 compatibility
+
Issue #2379 - Make various improvements to the NULL/DEFAULT handling in the data editor
+
Issue #2405 - Ensure object names are properly escaped for external process management
+
Issue #2410 - Fix PostgreSQL 10.0 compatibility issues
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_6.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_6.html new file mode 100644 index 0000000000000000000000000000000000000000..a4248b80eba69e007775d9582b302d23adb60a38 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_1_6.html @@ -0,0 +1,327 @@ + + + + + + + + + + Version 1.6 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 1.6

+

Release date: 2017-07-13

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 1.5

+
+

Features

+
+
Issue #1344 - Allow the Query Tool, Debugger and web browser tabs to be moved to different monitors as desired
+
Issue #1533 - Set focus on the first enabled field when a dialogue is opened
+
Issue #1535 - Teach dialogues about Escape to cancel, Enter to Save/OK, and F1 for help
+
Issue #1971 - Retain column sizing in the Query Tool results grid when the same query is re-run multiple times in a row
+
Issue #1972 - Prompt the user to save dirty queries rather than discard them for a more natural workflow
+
Issue #2137 - On-demand loading for the Query Tool results
+
Issue #2191 - Add support for the hostaddr connection parameter. This helps us play nicely with Kerberos/SSPI and friends
+
Issue #2282 - Overhaul the query history tab to allow browsing of the history and full query text
+
Issue #2379 - Support inserting multiple new rows into a table without clicking Save for each row
+
Issue #2485 - Add a shortcut to reset the zoom level in the runtime
+
Issue #2506 - Allow the user to close the dashboard panel
+
Issue #2513 - Add preferences to enable brace matching and brace closing in the SQL editors
+
+
+
+

Bug fixes

+
+
Issue #1126 - Various FTS dictionary cleanups
+
Issue #1229 - Fix default values and SQL formatting for event triggers
+
Issue #1466 - Prevent attempts to debug procedures with variadic arguments
+
Issue #1525 - Make $ quoting consistent
+
Issue #1575 - Properly display security labels on EPAS 9.2+
+
Issue #1795 - Fix validation for external and range types
+
Issue #1813 - List packages in PPAS 9.2-9.4 when creating synonyms
+
Issue #1831 - Fix server stats display for EPAS 9.2, where inet needs casting to text for concatenation
+
Issue #1851 - Reverse engineer SQL for table-returning functions correctly
+
Issue #1860 - Ensure default values are honoured when adding/editing columns
+
Issue #1888 - Fix various issues with pgAgent job steps and schedules
+
Issue #1889 - Fix various issues with pgAgent job steps and schedules
+
Issue #1890 - Fix various issues with pgAgent job steps and schedules
+
Issue #1920 - Ensure saved passwords are effective immediately, not just following a restart when first saved
+
Issue #1928 - Fix the handling of double precision[] type
+
Issue #1934 - Fix import/export to work as expected with TSV data
+
Issue #1999 - Handle warning correctly when saving query results to an unmounted USB drive
+
Issue #2013 - Increase the default size of the Grant Wizard to enable it to properly display privileges at the default size on smaller displays
+
Issue #2014 - To fix unexpected behaviour displayed if user stops debugging on package/procedure fire_emp
+
Issue #2043 - Properly handle trigger functions with parameters
+
Issue #2078 - Refresh the SQL editor view on resize to ensure the contents are re-rendered for the new viewport
+
Issue #2086 - Allow editing of the WITH ADMIN option of role membership
+
Issue #2113 - Correct the validation logic when modifying indexes/exclusion constraints
+
Issue #2116 - Enable dialogue help buttons on Language and Foreign Table dialogues
+
Issue #2142 - Fix canceling of Grant Wizard on Windows
+
Issue #2155 - Fix removal of sizes from column definitions
+
Issue #2162 - Allow non-superusers to debug their own functions and prevent them from setting global breakpoints
+
Issue #2242 - Fix an issue in NodeAjaxControl caching with cache-node field and add cache-node field in Trigger & Event trigger node so that whenever the user creates new Trigger Function we get new data from server in NodeAjaxControl
+
Issue #2280 - Handle procedure flags (IMMUTABLE STRICT SECURITY DEFINER PARALLEL RESTRICTED) properly in RE-SQL on EPAS
+
Issue #2324 - Fix the PostGIS Datatypes in SQL tab, Create / Update dialogues for Table, Column, Foreign Table and Type node
+
Issue #2344 - Fix issue with ctrl-c / ctrl-v not working in Query Tool
+
Issue #2348 - Fix issue when resizing columns in Query Too/View Data where all row/colums will select/deselect
+
Issue #2355 - Properly refresh the parent node when renaming children
+
Issue #2357 - Cache statistics more reliably
+
Issue #2381 - Fix the RE-SQL for for views to properly qualify trigger function names
+
Issue #2386 - Display and allow toggling of trigger enable/disable status from the trigger dialogue
+
Issue #2398 - Bypass the proxy server for local addresses on Windows
+
Issue #2400 - Cleanup handling of default/null values when data editing
+
Issue #2414 - Improve error handling in cases where the user tries to rename or create a server group that would duplicate an existing group
+
Issue #2417 - Order columns in multi-column pkeys correctly
+
Issue #2422 - Fix RE-SQL for rules which got the table name wrong in the header and DROP statement
+
Issue #2425 - Handle composite primary keys correctly when deleting rows in the Edit Grid
+
Issue #2426 - Allow creation of ENUM types with no members
+
Issue #2427 - Add numerous missing checks to ensure objects really exist when we think they do
+
Issue #2435 - Pass the database ID to the Query Tool when using the Script options
+
Issue #2436 - Ensure the last placeholder is included when generating UPDATE scripts for tables
+
Issue #2448 - Ensure that boolean checkboxes cycle values in the correct order
+
Issue #2450 - Fix error on the stats tab with PG10. Also, rename the 10.0_plus template directory to 10_plus to match the new versioning
+
Issue #2461 - Allow users to remove default values from columns properly
+
Issue #2468 - Fix issue where function create script won’t compile
+
Issue #2470 - Fix an intermittent error seen during result polling
+
Issue #2476 - Improvements to the Query Results grid including improvements to the UI and allow copy/paste from sets of rows, columns or arbitrary blocks of cells
+
Issue #2477 - Ensure text editors render in an appropriate place on the results grid
+
Issue #2479 - No need for the menu icon to link to the homepage, as pgAdmin is a SPA
+
Issue #2482 - Use a more sensible name for Query Tool tabs
+
Issue #2486 - Ensure the feature tests use the correct test settings database
+
Issue #2487 - Maintain a client-side cache of preference values, populated using an async call
+
Issue #2489 - Fix clipboard handling with large datasets
+
Issue #2492 - Ensure the initial password is properly hashed during setup in web mode
+
Issue #2498 - Properly handle bytea[], and ‘infinity’::real/real[]
+
Issue #2502 - Properly handle bytea[], and ‘infinity’::real/real[]
+
Issue #2503 - Handle missing/dropped synonyms gracefully
+
Issue #2504 - Update MatView and pgAgent modules to work with recent integer/numeric changes
+
Issue #2507 - Ensure revoked public privileges are displayed in the RE-SQL for functions
+
Issue #2518 - Fix encoding issue when saving servers
+
Issue #2522 - Improve speed of Select All in the results grid
+
Issue #2527 - Fix deletion of table rows with the column definition having NOT NULL TRUE and HAS NO DEFAULT VALUE
+
Issue #2528 - Allow breakpoints to be set on triggers on views
+
Issue #2529 - Resolve a number of issues with domains and domain constraints
+
Issue #2532 - Refresh nodes correctly when there is a single child that is updated
+
Issue #2534 - Fix handling of CREATE TABLE OF <type>
+
Issue #2535 - Fix clear history functionality
+
Issue #2540 - Ensure the save password option is enabled when creating a server
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_2_0.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_2_0.html new file mode 100644 index 0000000000000000000000000000000000000000..8e25cfb9097aaf24e423fb67aad28eb4c7b1de2d --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_2_0.html @@ -0,0 +1,316 @@ + + + + + + + + + + Version 2.0 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 2.0

+

Release date: 2017-10-05

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 1.6

+
+

Features

+
+
Issue #1918 - Add a field to the Server Dialogue allowing users to specify a subset of databases they’d like to see in the treeview
+
Issue #2135 - Significantly speed up loading of the application
+
Issue #2556 - Allow for slow vs. fast connection failures
+
Issue #2579 - Default the file browser view to list, and make it configurable
+
Issue #2597 - Allow queries to be cancelled from the dashboard and display additional info in the subnode control
+
Issue #2649 - Support use of SSL certificates for authentication
+
Issue #2650 - Support use of pgpass files
+
Issue #2662 - Ship with pre-configured paths that can work in both Server and Desktop modes out of the box
+
Issue #2689 - Update icons with new designs and remove from menus to de-clutter the UI
+
+
+
+

Bug fixes

+
+
Issue #1165 - Prevent continual polling for graph data on the dashboard if the server is disconnected
+
Issue #1697 - Update CodeMirror version
+
Issue #2043 - Properly handle trigger functions with parameters
+
Issue #2074 - Make $ quoting consistent
+
Issue #2080 - Fix issue where Browser hangs/crashes when loading data (using sql editor) from table which contains large blob data
+
Issue #2153 - Fix handline of large file uploads and properly show any errors that may occur
+
Issue #2168 - Update CodeMirror version
+
Issue #2170 - Support SSL in the regression tests
+
Issue #2324 - Fix PostGIS Datatypes in SQL tab, Create / Update dialogues for Table, Column, Foreign Table and Type node
+
Issue #2447 - Update CodeMirror version
+
Issue #2452 - Install pgadmin4-v1 1.5 on Centos7
+
Issue #2501 - Fix collation tests on Windows, replace use of default ‘POSIX’ collation with ‘C’ collation for testing
+
Issue #2541 - Fix issues using special keys on MacOS
+
Issue #2544 - Correct malformed query generated when using custom type
+
Issue #2551 - Show tablespace on partitions
+
Issue #2555 - Fix issue in Query Tool where messages were not displaying from functions/procedures properly
+
Issue #2557 - Tidy up tab styling
+
Issue #2558 - Prevent the tab bar being hidden when detached tabs are being closed
+
Issue #2559 - Stop tool buttons from changing their styling unexpectedly
+
Issue #2560 - Fix View ‘CREATE Script’ Problem
+
Issue #2562 - Update CodeMirror version
+
Issue #2563 - Fix paths under non-standard virtual directories
+
Issue #2566 - Fix Pause/Resume Replay of WAL files for PostgreSQL 10
+
Issue #2567 - Use the proper database connection to fetch the default priviledges in the properties tab of the database
+
Issue #2582 - Unset compression ratio if it is an empty string in Backup module
+
Issue #2586 - Cleanup feature tests
+
Issue #2590 - Allow navigation of query history using the arrow keys
+
Issue #2592 - Stop Flask from initialising service twice in Debug mode
+
Issue #2593 - Ensure babel-polyfill is loaded in older qWebKits
+
Issue #2594 - Fix disconnection of new databases
+
Issue #2596 - Define the proper NODE_ENV environment during running the webpack
+
Issue #2606 - Ensure role names are escaped in the membership control
+
Issue #2616 - Domain create dialog do not open and Font size issue in Security label control
+
Issue #2617 - Add missing pgagent file in webpack.config.js
+
Issue #2619 - Fix quoting of index column names on tables
+
Issue #2620 - Set database name to blank(‘’) when job type is set to batch, while creating pgAgent job
+
Issue #2631 - Change mapping of cell from ‘numeric’ to ‘integer’ for integer control as numeric cell has been removed from the code
+
Issue #2633 - Fix pgAgent job step issues
+
Issue #2634 - Add New Server through Quick links
+
Issue #2637 - Fix Copy so it still works after query results have been copied
+
Issue #2641 - User management issues - styling and inability to edit users properly
+
Issue #2644 - Fix alertify notification messages where checkmark box disconnected from frame
+
Issue #2646 - Fix the path reference of load-node.gif which was referencing to vendor directory
+
Issue #2654 - Update datetime picker
+
Issue #2655 - Fix connection string validation for pgAgent jobs
+
Issue #2656 - Change Datetimepicker to expand from bottom in pgAgent so calendar does not get hidden
+
Issue #2657 - Fix syntax error while saving changes for start/end time, weekdays, monthdays, month, hours, minutes while updating the pgAgent Job
+
Issue #2659 - Fix issue where unable to add/update variables for columns of a table
+
Issue #2660 - Not able to select rows in History Tab
+
Issue #2668 - Fix RE-SQL for triggers with a single arg
+
Issue #2670 - Improve datamodel validations for default Validator if user (developer) does not implement validate function in datamodel
+
Issue #2671 - Fix array data type formating for bigint, real, float, double precision
+
Issue #2681 - Reset Query Tool options before running tests
+
Issue #2684 - Fix layout of password prompt dialogue
+
Issue #2691 - View data option is missing from pgAdmin4 2.0 version
+
Issue #2692 - Base type is missing for Domain on pgAdmin4
+
Issue #2693 - User list is not available on User mapping pgAdmin4
+
Issue #2698 - User can not create function due to missing return type
+
Issue #2699 - Filtered Rows issue on pgAdmin4
+
Issue #2700 - Cancel button is visible after query executed succesfully
+
Issue #2707 - Disable trigger button does not work on pgAdmin4
+
Issue #2708 - Tablespace name should displayed instead of %s(new_tablespace)s with Move Objects to another tablespace
+
Issue #2709 - Display user relations in schema prefixed by ‘pg’
+
Issue #2713 - Fix an exception seen sometimes when the server is restarted
+
Issue #2742 - Ensure using an alternate role to connect to a database doesn’t cause an error when checking recovery state.
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_2_1.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_2_1.html new file mode 100644 index 0000000000000000000000000000000000000000..198a8584192b0a756b4bce2ddbb2046b384cefb0 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_2_1.html @@ -0,0 +1,315 @@ + + + + + + + + + + Version 2.1 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 2.1

+

Release date: 2018-01-11

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 2.0

+
+

Features

+
+
Issue #1383 - Allow connections to be coloured in the treeview and Query Tool
+
Issue #1489 - Improve user interface for selection query in Data Filter window
+
Issue #2368 - Improve data entry in Query Tool
+
Issue #2781 - Allow configuration of CSV and clipboard formatting of query results
+
Issue #2802 - Allow connections to be coloured in the treeview and Query Tool.
+
Issue #2810 - Allow files to be opened by double clicking on them within Query Tool
+
Issue #2845 - Make the “Save Changes” prompts in the Query Tool optional
+
Issue #2849 - Add support for editing data in tables with OIDs but no primary keys and updates the editor to retrieve all row values on save, thus immediately showing default values and allowing subsequent editing without a refresh
+
+
+
+

Bug fixes

+
+
Issue #1365 - Prevent the Windows installer accepting paths containing invalid characters
+
Issue #1366 - Fix /NOICONS switch in the windows installer
+
Issue #1436 - Fix issue with debugger which is failing for sub - procedure on PPAS 9.6
+
Issue #1749 - Fixes in pgAgent module including; 1) allowing start date earlier than end date when scheduling job, 2) Datetime picker not displaying in grid and 3) validation error not displaying propertly for Datetime control
+
Issue #2094 - Display relevant error messages when access is denied creating a schema
+
Issue #2098 - Cleanup some inconsistent error dialog titles
+
Issue #2258 - Fix handling of DATERANGE[] type
+
Issue #2278 - Display long names appropriately in dialogue headers
+
Issue #2443 - Confirm with the user before exiting the runtime
+
Issue #2524 - Fix debugging of self-referencing functions
+
Issue #2566 - Fix the Pause/Resume Replay of WAL files for PostgreSQL 10
+
Issue #2624 - Ensure the switch animation is consistent on the table dialogue and avoid displaying an error incorrectly
+
Issue #2651 - Ensure estimated rows are included correctly in CREATE script for functions
+
Issue #2679 - Getting started links does not open second time if User open any URL and Click on Close button with cross bar
+
Issue #2705 - User can add expirty date on Windows
+
Issue #2715 - Ensure we can download large files and keep the user informed about progress
+
Issue #2720 - Ensure password changes are successful if authenticating using a pgpass file
+
Issue #2726 - Ensure the auto-complete selection list can display longer names
+
Issue #2738 - Ensure line numbers form CodeMirror don’t appear on top of menus
+
Issue #2748 - Format JSON/JSONB nicely when displaying it in the grid editor pop-up
+
Issue #2760 - When selecting an SSL cert or key, update only the expected path in the UI, not all of them
+
Issue #2765 - Do not decrypt the password when the password is ‘None’. This should avoid the common but harmless exception “ValueError: IV must be 16 bytes long while decrypting the password.”
+
Issue #2768 - Only allow specification of a pgpass file if libpq >= 10
+
Issue #2769 - Correct keyboard shortcut. Don’t un-comment code with alt+. in the Query Tool. It’s only supposed to respond to ctrl/cmd+
+
Issue #2772 - Remove external links from Panel’s context menu
+
Issue #2778 - Ensure the datatype cache is updated when a domain is added
+
Issue #2779 - Ensure column collation isn’t lost when changing field size
+
Issue #2780 - Ensure auto-indent honours the spaces/tabs config setting
+
Issue #2782 - Re-hash the way that we handle rendering of special types such as arrays
+
Issue #2787 - Quote the owner name when creating types
+
Issue #2806 - Attempt to decode database errors based on lc_messages
+
Issue #2811 - Display process output as it happens
+
Issue #2820 - Logs available when executing backup and restore
+
Issue #2821 - Attempt to decode database errors based on lc_messages
+
Issue #2822 - Re-hash the way that we handle rendering of special types such as arrays.
+
Issue #2824 - Fix a number of graphical explain rendering issues
+
Issue #2836 - Fix counted rows display in table properties
+
Issue #2842 - Fix a number of graphical explain rendering issues
+
Issue #2846 - Add an option to manually count rows in tables to render the properties
+
Issue #2854 - Fix utility output capture encoding
+
Issue #2859 - Allow form validation messages to be close in case the eclipse anything on the form
+
Issue #2866 - Ensure we don’t show the full path on the server when using virtual filesystem roots in server mode for SSL certs
+
Issue #2875 - Ensure the scroll location is retains in the Query Tool data grid if the user changes tab and then returns
+
Issue #2877 - Remove the artificial limit of 4000 characters from text areas
+
Issue #2880 - Honour whitespace properly in the data grid
+
Issue #2881 - Fix support for time without timezone
+
Issue #2886 - Resolve issue where Insert failed when tried with default primary key value
+
Issue #2891 - Allow changing of the users password without leaving the app
+
Issue #2892 - Refuse password changes (and tell the user) if the notification email cannot be sent
+
Issue #2908 - Fix bundle creation on Windows which was failing due to rn line endings in code mirror
+
Issue #2918 - Add missing init.py to backports.csv when building the MSVC windows build
+
Issue #2920 - Push HTTPD logs to container stdout/stderr as appropriate
+
Issue #2921 - Fixes in pgAgent module including; 1) allowing start date earlier than end date when scheduling job, 2) Datetime picker not displaying in grid and 3) validation error not displaying propertly for Datetime control
+
Issue #2922 - Don’t login the user with every request in desktop mode. Just do it once
+
Issue #2923 - Prevent the user pressing the select button in the file manager when it is supposed to be disabled
+
Issue #2924 - Cleanup the layout of the filter data dialogue
+
Issue #2928 - Prevent multiple connections to new slow-to-respond servers being initiated in error
+
Issue #2934 - Fix a reference before assignment error in the file dialogue
+
Issue #2937 - Prevent attempts to select directories as files in the file dialogue
+
Issue #2945 - Ensure invalid options can’t be selected on triggers on views
+
Issue #2949 - Display complete SQL for FTS dictionaries
+
Issue #2952 - Don’t try to render security URLs in desktop mode
+
Issue #2954 - Allow selection of validation error text
+
Issue #2974 - Clear the messages tab when running EXPLAIN/EXPLAIN ANALYZE
+
Issue #2993 - Fix view data for views/mat views
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_0.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_0.html new file mode 100644 index 0000000000000000000000000000000000000000..16441517254c0d33132a9d2dcfe6b98487b38884 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_0.html @@ -0,0 +1,344 @@ + + + + + + + + + + Version 3.0 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 3.0

+

Release date: 2018-03-22

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 2.1

+
+

Features

+
+
Issue #1894 - Allow sorting when viewing/editing data
+
Issue #1978 - Add the ability to enable/disable UI animations
+
Issue #2895 - Add keyboard navigation options for the main browser windows
+
Issue #2896 - Add keyboard navigation in Query tool module via Tab/Shift-Tab key
+
Issue #2897 - Support keyboard navigation in the debugger
+
Issue #2898 - Support tab navigation in dialogs
+
Issue #2899 - Add configurable shortcut keys for various common options in the main window
+
Issue #2901 - Configurable shortcuts in the Debugger
+
Issue #2904 - Ensure clickable images/buttons have appropriate tooltips for screen readers
+
Issue #2950 - Add a marker (/pga4dash/) to the dashboard queries to allow them to be more easily filtered from server logs
+
Issue #2951 - Allow dashboard tables and charts to be enabled/disabled
+
Issue #3004 - Support server and database statistics on Greenplum
+
Issue #3036 - Display partitions in Greenplum
+
Issue #3044 - Display functions in Greenplum
+
Issue #3086 - Rewrite the runtime as a tray-based server which can launch a web browser
+
Issue #3097 - Support EXPLAIN on Greenplum
+
Issue #3098 - Unvendorize REACT so no longer required in our source tree
+
Issue #3107 - Hide tablespace node on GPDB
+
Issue #3140 - Add support for connecting using pg_service.conf files
+
Issue #3168 - Support for external tables in GPDB
+
Issue #3182 - Update Jasmine to v3
+
Issue #3184 - Add a French translation
+
Issue #3195 - Pass the service name to external processes
+
Issue #3246 - Update container build to use Alpine Linux and Gunicorn instead of CentOS/Apache
+
+
+
In addition, various changes were made for PEP8 compliance
+
+
+
+

Bug fixes

+
+
Issue #1173 - Add a comment to the existing node
+
Issue #1925 - Fix issue resizing column widths not resizable in Query Tool after first query
+
Issue #2104 - Runtime update display file version and copyright year under installers properties
+
Issue #2249 - Application no longer hangs after reload in runtime
+
Issue #2251 - Runtime fixed OSX html scroll direction ignored in MacOS setup
+
Issue #2309 - Allow text selection/copying from disabled CodeMirror instances
+
Issue #2480 - Runtime update fix to Context Menus on Mac that do not work
+
Issue #2578 - Runtime update fix to HTML access keys that don’t work
+
Issue #2581 - Fix keyboard shortcut for text selection
+
Issue #2677 - Update Elephant icon for pgAdmin4 on Windows
+
Issue #2776 - Fix unreadable font via Remote Desktop
+
Issue #2777 - Fix spacing issue on server tree
+
Issue #2783 - Runtime update fixed blank screen on Windows Desktop
+
Issue #2906 - Correct display issues on HiDPI screens
+
Issue #2961 - Issues when creating a pgAgent Schedule
+
Issue #2963 - Fix unicode handling in the external process tools and show the complete command in the process viewer
+
Issue #2980 - Copy text from the Query tool into the clipboard adds invisible characters
+
Issue #2981 - Support keyboard navigation in the debugger
+
Issue #2983 - Fix intermittent specified_version_number ValueError issue on restart
+
Issue #2985 - Fix drag and drop issues
+
Issue #2998 - Don’t listen on port 443 if TLS is not enabled when launching the container
+
Issue #3001 - Runtime update fix scrolling with mouse wheel on mac pgAdmin 4.2.1
+
Issue #3002 - Fix block indent/outdent with configurable width
+
Issue #3003 - Runtime update fix copy to clipboard
+
Issue #3005 - Runtime update fix unable to select tabs in pgAdmin 4.2.1
+
Issue #3013 - Fix a minor UI issue on dashboard while displaying subnode control in Backgrid
+
Issue #3014 - Fix validation of sequence parameters
+
Issue #3015 - Support Properties on Greenplum databases
+
Issue #3016 - Ensure debug messages are available in “messages” window when error occurs
+
Issue #3021 - Update scan and index scan EXPLAIN icons for greater clarity
+
Issue #3027 - Ensure we capture notices raised by queries
+
Issue #3031 - Runtime issue causing double and single quotes not to work
+
Issue #3039 - Runtime issue causing wrong row counts on count column
+
Issue #3042 - Runtime issue causing empty dialog box when refreshing
+
Issue #3043 - Runtime issue causing word sizing in macOS High Sierra
+
Issue #3045 - Runtime issue causing copy cells issues copying cells for key binding
+
Issue #3046 - Fix connection status indicator on IE/FF
+
Issue #3050 - Correct display of RE-SQL for partitioned tables in Greenplum
+
Issue #3052 - Don’t include sizes on primitive data types that shouldn’t have them when modifying columns
+
Issue #3054 - Ensure the user can use keyboard shortcuts after using button controls such as Cancel, Open and Save
+
Issue #3057 - Update the regression tests to fix issues with Python 3.5 and PG 9.2
+
Issue #3058 - Fix on-click handling of treeview nodes that wasn’t refreshing SQL/Dependencies/Dependents in some circumstances
+
Issue #3059 - Fix table statistics for Greenplum
+
Issue #3060 - Fix quoting of function names in RE-SQL
+
Issue #3066 - Ensure column names on indexes on views are properly quoted in RE-SQL
+
Issue #3067 - Prevent the filter dialog CodeMirror from overflowing onto the button bar of the dialog
+
Issue #3072 - Add a (configurable) limit to the number of pgAgent job history rows displayed on the statistics tab
+
Issue #3073 - Ensure the pgAgent job start/end time grid fields synchronise with the subnode control and validate correctly
+
Issue #3075 - Runtime issue causing Select, Update, and Insert script generation for a table fails to load
+
Issue #3077 - Remove dependency on standards_conforming_strings being enabled
+
Issue #3079 - Fix handling of tie/datetime array types when adding columns to a table
+
Issue #3080 - Fix alignment issues in keyboard shortcut options
+
Issue #3081 - Add missing reverse-engineered SQL header and drop statement for sequences
+
Issue #3090 - Ensure message severity is decoded when necessary by the driver
+
Issue #3094 - Ensure all messages are retrieved from the server in the Query Tool
+
Issue #3099 - Fix creation of tables and columns in GPDB
+
Issue #3105 - Ensure we can properly update rows with upper-case primary key columns
+
Issue #3135 - Insert rows correctly when a table has OIDs and a Primary Key in uppercase
+
Issue #3122 - Ensure SSL options are pushed down to external tools like pg_dump
+
Issue #3129 - Handle opening of non-UTF8 compatible files
+
Issue #3137 - Allow copying of SQL from the dashboard tables
+
Issue #3138 - Fix tablespace tests for Python 3.x
+
Issue #3150 - Fix function reserve SQL for GPDB
+
Issue #3157 - Fix unicode handling in the external process tools and show the complete command in the process viewer
+
Issue #3171 - Runtime issue causing inability to scroll in File Selector with trackpad on OSX
+
Issue #3176 - Disable function statistics on Greenplum
+
Issue #3180 - Ensure Indexes are displayed on PG 10 tables
+
Issue #3190 - Skip tests where appropriate on GPDB
+
Issue #3196 - Ensure the file manager properly escapes file & directory names
+
Issue #3197 - Appropriately set the cookie path
+
Issue #3200 - Ensure the host parameter is correctly pickup up from the service file
+
Issue #3219 - Update required ChromeDriver version for current versions of Chrome
+
Issue #3226 - Move the field error indicators in front of the affected fields so they don’t obscure spinners or drop downs etc.
+
Issue #3244 - Show more granular timing info in the Query Tool history panel
+
Issue #3248 - Ensure Alertify dialogues are modal to prevent them being closed by mis-click
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_1.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_1.html new file mode 100644 index 0000000000000000000000000000000000000000..74a67af12bef5176d6156be7294b9b2b41b10753 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_1.html @@ -0,0 +1,275 @@ + + + + + + + + + + Version 3.1 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 3.1

+

Release date: 2018-06-28

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 3.0

+
+

Features

+
+
Issue #1447 - Add support for SSH tunneled connections
+
Issue #2686 - Add an option to auto-complete keywords in upper case
+
Issue #3204 - Add support for LISTEN/NOTIFY in the Query Tool
+
Issue #3273 - Allow sorting in the file dialogue
+
Issue #3362 - Function and procedure support for PG11
+
Issue #3388 - Allow the connection timeout to be configured on a per-server basis
+
+
+
+

Bug fixes

+
+
Issue #1220 - Backup and Restore should not be started if database name contains “=” symbol
+
Issue #1221 - Maintenance should not be started if database name contains “=” symbol
+
Issue #3179 - Fix an error generating SQL for trigger functions
+
Issue #3238 - Standardise the error handling for parsing of JSON response messages from the server
+
Issue #3250 - Fix handling of SQL_ASCII data in the Query Tool
+
Issue #3257 - Catch errors when trying to EXPLAIN an invalid query
+
Issue #3277 - Ensure server cleanup on exit only happens if the server actually started up
+
Issue #3284 - F5 key should work to refresh Browser tree
+
Issue #3289 - Fix handling of SQL_ASCII data in the Query Tool
+
Issue #3290 - Close button added to the alertify message box, which pops up in case of backend error
+
Issue #3295 - Ensure the debugger gets focus when loaded so shortcut keys work as expected
+
Issue #3298 - Fixed Query Tool keyboard issue where arrow keys were not behaving as expected for execute options dropdown
+
Issue #3303 - Fix a Japanese translation error that could prevent the server starting up
+
Issue #3306 - Fixed display SQL of table with index for Greenplum database
+
Issue #3307 - Allow connections to servers with port numbers < 1024 which may be seen in container environments
+
Issue #3308 - Fixed issue where icon for Partitioned tables was the same as Non Partitioned tables for Greenplum database
+
Issue #3310 - Fixed layout of the alertify error message in the Query Tool
+
Issue #3324 - Fix the template loader to work reliably under Windows (fixing external tables under Greenplum)
+
Issue #3333 - Ensure the runtime core application is setup before trying to access any settings
+
Issue #3342 - Set SESSION_COOKIE_SAMESITE=’Lax’ per Flask recommendation to prevents sending cookies with CSRF-prone requests from external sites, such as submitting a form
+
Issue #3353 - Handle errors properly if they occur when renaming a database
+
Issue #3356 - Include the schema name on RE-SQL for packages
+
Issue #3374 - Fix autocomplete
+
Issue #3392 - Fix IPv6 support in the container build
+
Issue #3409 - Avoid an exception on GreenPlum when retrieving RE-SQL on a table
+
Issue #3411 - Fix a French translation error that could prevent the server starting up
+
Issue #3431 - Fix the RE-SQL generation for GreenPlum external tables
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_2.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_2.html new file mode 100644 index 0000000000000000000000000000000000000000..68d449547c0b24b0a3ee04e4ea1626b6c64b2341 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_2.html @@ -0,0 +1,266 @@ + + + + + + + + + + Version 3.2 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 3.2

+

Release date: 2018-08-09

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 3.1

+
+

Features

+
+
Issue #2136 - Added version number for URL’s to ensure that files are only cached on a per-version basis.
+
Issue #2214 - Add support for SCRAM password changes (requires psycopg2 >= 2.8).
+
Issue #3074 - Add support for reset saved password.
+
Issue #3397 - Add support for Trigger and JIT stats in the graphical query plan viewer.
+
Issue #3412 - Add support for primary key, foreign key, unique key, indexes and triggers on partitioned tables for PG/EPAS 11.
+
Issue #3506 - Allow the user to specify a fixed port number in the runtime to aid cookie whitelisting etc.
+
Issue #3510 - Add a menu option to the runtime to copy the appserver URL to the clipboard.
+
+
+
+

Bug fixes

+
+
Issue #3185 - Fix the upgrade check on macOS.
+
Issue #3191 - Fix a number of debugger execution issues.
+
Issue #3294 - Infrastructure (and changes to the Query Tool, Dashboards and Debugger) for realtime preference handling.
+
Issue #3309 - Fix Directory format support for backups.
+
Issue #3316 - Support running on systems without a system tray.
+
Issue #3319 - Cleanup and fix handling of Query Tool Cancel button status.
+
Issue #3363 - Fix restoring of restore options for sections.
+
Issue #3371 - Don’t create a session when the /misc/ping test endpoint is called.
+
Issue #3446 - Various procedure/function related fixes for EPAS/PG 11.
+
Issue #3448 - Exclude system columns in Import/Export.
+
Issue #3457 - Fix debugging of procedures in EPAS packages.
+
Issue #3458 - pgAdmin4 should work with python 3.7.
+
Issue #3468 - Support SSH tunneling with keys that don’t have a passphrase.
+
Issue #3471 - Ensure the SSH tunnel port number is honoured.
+
Issue #3511 - Add support to save and clear SSH Tunnel password.
+
Issue #3526 - COST statement should not be automatically duplicated after creating trigger function.
+
Issue #3527 - View Data->Filtered Rows dialog should be displayed.
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_3.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_3.html new file mode 100644 index 0000000000000000000000000000000000000000..34612616ea5336956af939d0605c305277c330c8 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_3.html @@ -0,0 +1,263 @@ + + + + + + + + + + Version 3.3 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 3.3

+

Release date: 2018-09-06

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 3.2

+
+

Features

+
+
Issue #1407 - Add a geometry viewer that can render PostGIS data on a blank canvas or various map sources.
+
Issue #3503 - Added new backup/restore options for PostgreSQL 11. Added dump options for ‘pg_dumpall’.
+
Issue #3553 - Add a Spanish translation.
+
+
+
+

Bug fixes

+
+
Issue #3136 - Stabilise feature tests for continuous running on CI systems.
+
Issue #3191 - Fixed debugger execution issues.
+
Issue #3313 - Ensure ‘select all’ and ‘unselect all’ working properly for pgAgent schedule.
+
Issue #3325 - Fix sort/filter dialog issue where it incorrectly requires ASC/DESC.
+
Issue #3347 - Ensure backup should work with ‘–data-only’ and ‘–schema-only’ for any format.
+
Issue #3407 - Fix keyboard shortcuts layout in the preferences panel.
+
Issue #3420 - Merge pgcli code with version 1.10.3, which is used for auto complete feature.
+
Issue #3461 - Ensure that refreshing a node also updates the Property list.
+
Issue #3525 - Ensure that refresh button on dashboard should refresh the table.
+
Issue #3528 - Handle connection errors properly in the Query Tool.
+
Issue #3547 - Make session implementation thread safe
+
Issue #3548 - Ensure external table node should be visible only for GPDB.
+
Issue #3554 - Fix auto scrolling issue in debugger on step in and step out.
+
Issue #3558 - Fix sort/filter dialog editing issue.
+
Issue #3561 - Ensure sort/filter dialog should display proper message after losing database connection.
+
Issue #3578 - Ensure sql for Role should be visible in SQL panel for GPDB.
+
Issue #3579 - When building the Windows installer, copy system Python packages before installing dependencies to ensure we don’t end up with older versions than intended.
+
Issue #3604 - Correct the documentation of View/Edit data.
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_4.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_4.html new file mode 100644 index 0000000000000000000000000000000000000000..846173889c03beaf024f9c6081d43516ba68c537 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_4.html @@ -0,0 +1,253 @@ + + + + + + + + + + Version 3.4 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 3.4

+

Release date: 2018-10-04

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 3.3

+
+

Features

+
+
Issue #2927 - Move all CSS into SCSS files for consistency and ease of colour maintenance etc.
+
Issue #3514 - Add optional data point markers and mouse-over tooltips to display values on graphs.
+
Issue #3564 - Add shortcuts for View Data and the Query tool to the Browser header bar.
+
+
+
+

Bug fixes

+
+
Issue #3464 - Ensure the runtime can startup properly if there are wide characters in the logfile path on Windows.
+
Issue #3551 - Fix handling of backslashes in the edit grid.
+
Issue #3576 - Ensure queries are no longer executed when dashboards are closed.
+
Issue #3596 - Fix support for the CLOB datatype in EPAS.
+
Issue #3607 - Fix logic around validation and highlighting of Sort/Filter in the Query Tool.
+
Issue #3630 - Ensure auto-complete works for objects in schemas other than public and pg_catalog.
+
Issue #3657 - Ensure changes to Query Tool settings from the Preferences dialogue are applied before executing queries.
+
Issue #3658 - Swap the Schema and Schemas icons and Catalog and Catalogs icons that had been used the wrong way around.
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_5.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_5.html new file mode 100644 index 0000000000000000000000000000000000000000..2f0e9af915d5cf0feeb8966d789cfd2d849e8813 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_5.html @@ -0,0 +1,253 @@ + + + + + + + + + + Version 3.5 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 3.5

+

Release date: 2018-11-01

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 3.4

+
+

Features

+
+
Issue #1253 - Save the treeview state periodically, and restore it automatically when reconnecting.
+
Issue #3562 - Migrate from Bootstrap 3 to Bootstrap 4.
+
+
+
+

Bug fixes

+
+
Issue #3232 - Ensure that Utilities(Backup/Restore/Maintenence/Import-Export) should not be started if binary path is wrong and also added ‘Stop Process’ button to cancel the process.
+
Issue #3638 - Fix syntax error when creating new pgAgent schedules with a start date/time and exception.
+
Issue #3674 - Cleanup session files periodically.
+
Issue #3660 - Rename the ‘SQL Editor’ section of the Preferences to ‘Query Tool’ as it applies to the whole tool, not just the editor.
+
Issue #3676 - Fix CREATE Script functionality for EDB-Wrapped functions.
+
Issue #3700 - Fix connection garbage collector.
+
Issue #3703 - Purge connections from the cache on logout.
+
Issue #3722 - Ensure that utility existence check should work for schema and other child objects while taking Backup/Restore.
+
Issue #3730 - Fixed fatal error while launching the pgAdmin4 3.5. Update the version of the Flask to 0.12.4 for release.
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_6.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_6.html new file mode 100644 index 0000000000000000000000000000000000000000..5e1bf5acee9dfdfdf775b4b2779d97045e167532 --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_3_6.html @@ -0,0 +1,252 @@ + + + + + + + + + + Version 3.6 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 3.6

+

Release date: 2018-11-29

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 3.5

+
+

Features

+
+
Issue #1513 - Add support for dropping multiple objects at once from the collection Properties panel.
+
Issue #3772 - Add the ability to import and export server definitions from a config database.
+
+
+
+

Bug fixes

+
+
Issue #3016 - Ensure previous notices are not removed from the Messages tab in the Query Tool if an error occurs during query execution.
+
Issue #3029 - Allow the selection order to be preserved in the Select2 control to fix column ordering in data Import/Export.
+
Issue #3629 - Allow use of 0 (integer) and empty strings as parameters in the debugger.
+
Issue #3723 - Properly report errors when debugging cannot be started.
+
Issue #3734 - Prevent the debugger controls being pressed again before previous processing is complete.
+
Issue #3736 - Fix toggle breakpoints buttons in the debugger.
+
Issue #3742 - Fix changes to the NOT NULL and default value options in the Table Dialogue.
+
Issue #3746 - Fix dropping of multiple functions/procedures at once.
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_4_0.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_4_0.html new file mode 100644 index 0000000000000000000000000000000000000000..44e8ecc39a7845818cc42292b18912ef10cda11e --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_4_0.html @@ -0,0 +1,268 @@ + + + + + + + + + + Version 4.0 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 4.0

+

Release date: 2019-01-10

+

This release contains a number of features and fixes reported since the release +of pgAdmin4 3.6

+
+

Features

+
+
Issue #3589 - Allow query plans to be downloaded as an SVG file.
+
Issue #3692 - New UI design.
+
Issue #3801 - Allow servers to be pre-loaded into container deployments.
+
+
+
+

Bug fixes

+
+
Issue #3083 - Increase the size of the resize handle of the edit grid text pop-out.
+
Issue #3354 - Fix handling of array types as inputs to the debugger.
+
Issue #3433 - Fix an issue that could cause the Query Tool to fail to render.
+
Issue #3549 - Display event trigger functions correctly on EPAS.
+
Issue #3559 - Further improvements to treeview restoration.
+
Issue #3599 - Run Postfix in the container build so passwords can be reset etc.
+
Issue #3619 - Add titles to the code areas of the Query Tool and Debugger to ensure that panels can be re-docked within them.
+
Issue #3679 - Fix a webpack issue that could cause the Query Tool to fail to render.
+
Issue #3702 - Ensure we display the relation name (and not the OID) in the locks table wherever possible.
+
Issue #3711 - Fix an encoding issue in the Query Tool.
+
Issue #3726 - Include the WHERE clause on EXCLUDE constraints in RE-SQL.
+
Issue #3753 - Fix an issue when user define Cast from smallint->text is created.
+
Issue #3757 - Hide Radio buttons that should not be shown on the maintenance dialogue.
+
Issue #3780 - Ensure that null values handled properly in CSV download.
+
Issue #3796 - Tweak the wording on the Grant Wizard.
+
Issue #3797 - Prevent attempts to bulk-drop schema objects.
+
Issue #3798 - Ensure the browser toolbar buttons work in languages other than English.
+
Issue #3805 - Allow horizontal sizing of the edit grid text pop-out.
+
Issue #3809 - Ensure auto complete should works when first identifier in the FROM clause needs quoting.
+
Issue #3810 - Ensure auto complete should works for columns from a schema-qualified table.
+
Issue #3821 - Ensure identifiers are properly displayed in the plan viewer.
+
Issue #3830 - Make the setup process more robust against aborted executions.
+
Issue #3856 - Fixed an issue while creating export job.
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_4_1.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_4_1.html new file mode 100644 index 0000000000000000000000000000000000000000..2c55605c733a1720bdec366ae6c21c6143de756a --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_4_1.html @@ -0,0 +1,243 @@ + + + + + + + + + + Version 4.1 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 4.1

+

Release date: 2019-01-15

+

This release contains a number of fixes reported since the release of pgAdmin4 +4.0

+
+

Bug fixes

+
+
Issue #3505 - Fix SQL generated for tables with inherited columns.
+
Issue #3575 - Ensure the context menu works after a server is renamed.
+
Issue #3836 - Fix ordering of VACUUM options which changed in PG11.
+
Issue #3842 - Don’t show system catalogs in the schemas property list unless show system objects is enabled.
+
Issue #3861 - Fix help for the backup/restore dialogues.
+
Issue #3866 - Ensure that last row of table data should be visible and user will be able to add new row.
+
Issue #3877 - Make the browser more robust in the face of multibyte characters in SQL_ASCII databases.
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/docs/en_US/html/release_notes_4_10.html b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_4_10.html new file mode 100644 index 0000000000000000000000000000000000000000..b4c9cff2012d9c815baf69986566722a3071898f --- /dev/null +++ b/pgsql/pgAdmin 4/docs/en_US/html/release_notes_4_10.html @@ -0,0 +1,247 @@ + + + + + + + + + + Version 4.10 — pgAdmin 4 8.6 documentation + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Version 4.10

+

Release date: 2019-07-04

+

This release contains a number of bug fixes and new features since the release of pgAdmin4 4.9.

+
+

New features

+
+
Issue #4139 - Allow some objects to be dragged/dropped into the Query Tool to insert their signature into the query text.
+
Issue #4400 - Allow the path to /pgadmin4/servers.json to be overridden in the container distribution.
+
+
+
+

Bug fixes

+
+
Issue #4403 - Ensure the browser close confirmation is only shown when closing a Query Tool which is running in a separate browser tab.
+
Issue #4404 - Prevent an error that may occur when editing data with an integer primary key.
+
Issue #4407 - Fix a quoting issue that caused a blank UI to be displayed when running in French.
+
Issue #4421 - Ensure the version comparision should be correct for windows installer.
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/db_print.py b/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/db_print.py new file mode 100644 index 0000000000000000000000000000000000000000..c0eb83ee4dbae3b579dbfd63ccfc54748b6320d3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/db_print.py @@ -0,0 +1,72 @@ +""" db_print.py -- a simple demo for ADO database reads.""" + +import sys + +import adodbapi.ado_consts as adc + +cmd_args = ("filename", "table_name") +if "help" in sys.argv: + print("possible settings keywords are:", cmd_args) + sys.exit() + +kw_args = {} # pick up filename and proxy address from command line (optionally) +for arg in sys.argv: + s = arg.split("=") + if len(s) > 1: + if s[0] in cmd_args: + kw_args[s[0]] = s[1] + +kw_args.setdefault( + "filename", "test.mdb" +) # assumes server is running from examples folder +kw_args.setdefault("table_name", "Products") # the name of the demo table + +# the server needs to select the provider based on his Python installation +provider_switch = ["provider", "Microsoft.ACE.OLEDB.12.0", "Microsoft.Jet.OLEDB.4.0"] + +# ------------------------ START HERE ------------------------------------- +# create the connection +constr = "Provider=%(provider)s;Data Source=%(filename)s" +import adodbapi as db + +con = db.connect(constr, kw_args, macro_is64bit=provider_switch) + +if kw_args["table_name"] == "?": + print("The tables in your database are:") + for name in con.get_table_names(): + print(name) +else: + # make a cursor on the connection + with con.cursor() as c: + # run an SQL statement on the cursor + sql = "select * from %s" % kw_args["table_name"] + print('performing query="%s"' % sql) + c.execute(sql) + + # check the results + print( + 'result rowcount shows as= %d. (Note: -1 means "not known")' % (c.rowcount,) + ) + print("") + print("result data description is:") + print(" NAME Type DispSize IntrnlSz Prec Scale Null?") + for d in c.description: + print( + ("%16s %-12s %8s %8d %4d %5d %s") + % (d[0], adc.adTypeNames[d[1]], d[2], d[3], d[4], d[5], bool(d[6])) + ) + print("") + print("str() of first five records are...") + + # get the results + db = c.fetchmany(5) + + # print them + for rec in db: + print(rec) + + print("") + print("repr() of next row is...") + print(repr(c.fetchone())) + print("") +con.close() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/db_table_names.py b/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/db_table_names.py new file mode 100644 index 0000000000000000000000000000000000000000..2d7bf9df0d3eb89f46a48e2cc942a8eb9e7401b2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/db_table_names.py @@ -0,0 +1,20 @@ +""" db_table_names.py -- a simple demo for ADO database table listing.""" +import sys + +import adodbapi + +try: + databasename = sys.argv[1] +except IndexError: + databasename = "test.mdb" + +provider = ["prv", "Microsoft.ACE.OLEDB.12.0", "Microsoft.Jet.OLEDB.4.0"] +constr = "Provider=%(prv)s;Data Source=%(db)s" + +# create the connection +con = adodbapi.connect(constr, db=databasename, macro_is64bit=provider) + +print("Table names in= %s" % databasename) + +for table in con.get_table_names(): + print(table) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/xls_read.py b/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/xls_read.py new file mode 100644 index 0000000000000000000000000000000000000000..10bcc57e6bb77db9d10eddbf6d2ae71deb4eb601 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/xls_read.py @@ -0,0 +1,41 @@ +import sys + +import adodbapi + +try: + import adodbapi.is64bit as is64bit + + is64 = is64bit.Python() +except ImportError: + is64 = False + +if is64: + driver = "Microsoft.ACE.OLEDB.12.0" +else: + driver = "Microsoft.Jet.OLEDB.4.0" +extended = 'Extended Properties="Excel 8.0;HDR=Yes;IMEX=1;"' + +try: # first command line argument will be xls file name -- default to the one written by xls_write.py + filename = sys.argv[1] +except IndexError: + filename = "xx.xls" + +constr = "Provider=%s;Data Source=%s;%s" % (driver, filename, extended) + +conn = adodbapi.connect(constr) + +try: # second command line argument will be worksheet name -- default to first worksheet + sheet = sys.argv[2] +except IndexError: + # use ADO feature to get the name of the first worksheet + sheet = conn.get_table_names()[0] + +print("Shreadsheet=%s Worksheet=%s" % (filename, sheet)) +print("------------------------------------------------------------") +crsr = conn.cursor() +sql = "SELECT * from [%s]" % sheet +crsr.execute(sql) +for row in crsr.fetchmany(10): + print(repr(row)) +crsr.close() +conn.close() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/xls_write.py b/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/xls_write.py new file mode 100644 index 0000000000000000000000000000000000000000..38baefd8122fe0dfe83488ab317e5e51e57fd595 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/adodbapi/examples/xls_write.py @@ -0,0 +1,41 @@ +import datetime + +import adodbapi + +try: + import adodbapi.is64bit as is64bit + + is64 = is64bit.Python() +except ImportError: + is64 = False # in case the user has an old version of adodbapi +if is64: + driver = "Microsoft.ACE.OLEDB.12.0" +else: + driver = "Microsoft.Jet.OLEDB.4.0" +filename = "xx.xls" # file will be created if it does not exist +extended = 'Extended Properties="Excel 8.0;Readonly=False;"' + +constr = "Provider=%s;Data Source=%s;%s" % (driver, filename, extended) + +conn = adodbapi.connect(constr) +with conn: # will auto commit if no errors + with conn.cursor() as crsr: + try: + crsr.execute("drop table SheetOne") + except: + pass # just is case there is one already there + + # create the sheet and the header row and set the types for the columns + crsr.execute( + "create table SheetOne (Name varchar, Rank varchar, SrvcNum integer, Weight float, Birth date)" + ) + + sql = "INSERT INTO SheetOne (name, rank , srvcnum, weight, birth) values (?,?,?,?,?)" + + data = ("Mike Murphy", "SSG", 123456789, 167.8, datetime.date(1922, 12, 27)) + crsr.execute(sql, data) # write the first row of data + crsr.execute( + sql, ["John Jones", "Pvt", 987654321, 140.0, datetime.date(1921, 7, 4)] + ) # another row of data +conn.close() +print("Created spreadsheet=%s worksheet=%s" % (filename, "SheetOne")) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..445ddb25125aa63994052dd4ecea1362dc91656d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/__init__.py @@ -0,0 +1,10 @@ +from .api import _render_migration_diffs as _render_migration_diffs +from .api import compare_metadata as compare_metadata +from .api import produce_migrations as produce_migrations +from .api import render_python_code as render_python_code +from .api import RevisionContext as RevisionContext +from .compare import _produce_net_changes as _produce_net_changes +from .compare import comparators as comparators +from .render import render_op_text as render_op_text +from .render import renderers as renderers +from .rewriter import Rewriter as Rewriter diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/api.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/api.py new file mode 100644 index 0000000000000000000000000000000000000000..aa8f32f65359c9c04f41ea24e21131beee2d8d2a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/api.py @@ -0,0 +1,650 @@ +from __future__ import annotations + +import contextlib +from typing import Any +from typing import Dict +from typing import Iterator +from typing import List +from typing import Optional +from typing import Sequence +from typing import Set +from typing import TYPE_CHECKING +from typing import Union + +from sqlalchemy import inspect + +from . import compare +from . import render +from .. import util +from ..operations import ops +from ..util import sqla_compat + +"""Provide the 'autogenerate' feature which can produce migration operations +automatically.""" + +if TYPE_CHECKING: + from sqlalchemy.engine import Connection + from sqlalchemy.engine import Dialect + from sqlalchemy.engine import Inspector + from sqlalchemy.sql.schema import MetaData + from sqlalchemy.sql.schema import SchemaItem + from sqlalchemy.sql.schema import Table + + from ..config import Config + from ..operations.ops import DowngradeOps + from ..operations.ops import MigrationScript + from ..operations.ops import UpgradeOps + from ..runtime.environment import NameFilterParentNames + from ..runtime.environment import NameFilterType + from ..runtime.environment import ProcessRevisionDirectiveFn + from ..runtime.environment import RenderItemFn + from ..runtime.migration import MigrationContext + from ..script.base import Script + from ..script.base import ScriptDirectory + from ..script.revision import _GetRevArg + + +def compare_metadata(context: MigrationContext, metadata: MetaData) -> Any: + """Compare a database schema to that given in a + :class:`~sqlalchemy.schema.MetaData` instance. + + The database connection is presented in the context + of a :class:`.MigrationContext` object, which + provides database connectivity as well as optional + comparison functions to use for datatypes and + server defaults - see the "autogenerate" arguments + at :meth:`.EnvironmentContext.configure` + for details on these. + + The return format is a list of "diff" directives, + each representing individual differences:: + + from alembic.migration import MigrationContext + from alembic.autogenerate import compare_metadata + from sqlalchemy import ( + create_engine, + MetaData, + Column, + Integer, + String, + Table, + text, + ) + import pprint + + engine = create_engine("sqlite://") + + with engine.begin() as conn: + conn.execute( + text( + ''' + create table foo ( + id integer not null primary key, + old_data varchar, + x integer + ) + ''' + ) + ) + conn.execute(text("create table bar (data varchar)")) + + metadata = MetaData() + Table( + "foo", + metadata, + Column("id", Integer, primary_key=True), + Column("data", Integer), + Column("x", Integer, nullable=False), + ) + Table("bat", metadata, Column("info", String)) + + mc = MigrationContext.configure(engine.connect()) + + diff = compare_metadata(mc, metadata) + pprint.pprint(diff, indent=2, width=20) + + Output:: + + [ + ( + "add_table", + Table( + "bat", + MetaData(), + Column("info", String(), table=), + schema=None, + ), + ), + ( + "remove_table", + Table( + "bar", + MetaData(), + Column("data", VARCHAR(), table=), + schema=None, + ), + ), + ( + "add_column", + None, + "foo", + Column("data", Integer(), table=), + ), + [ + ( + "modify_nullable", + None, + "foo", + "x", + { + "existing_comment": None, + "existing_server_default": False, + "existing_type": INTEGER(), + }, + True, + False, + ) + ], + ( + "remove_column", + None, + "foo", + Column("old_data", VARCHAR(), table=), + ), + ] + + :param context: a :class:`.MigrationContext` + instance. + :param metadata: a :class:`~sqlalchemy.schema.MetaData` + instance. + + .. seealso:: + + :func:`.produce_migrations` - produces a :class:`.MigrationScript` + structure based on metadata comparison. + + """ + + migration_script = produce_migrations(context, metadata) + assert migration_script.upgrade_ops is not None + return migration_script.upgrade_ops.as_diffs() + + +def produce_migrations( + context: MigrationContext, metadata: MetaData +) -> MigrationScript: + """Produce a :class:`.MigrationScript` structure based on schema + comparison. + + This function does essentially what :func:`.compare_metadata` does, + but then runs the resulting list of diffs to produce the full + :class:`.MigrationScript` object. For an example of what this looks like, + see the example in :ref:`customizing_revision`. + + .. seealso:: + + :func:`.compare_metadata` - returns more fundamental "diff" + data from comparing a schema. + + """ + + autogen_context = AutogenContext(context, metadata=metadata) + + migration_script = ops.MigrationScript( + rev_id=None, + upgrade_ops=ops.UpgradeOps([]), + downgrade_ops=ops.DowngradeOps([]), + ) + + compare._populate_migration_script(autogen_context, migration_script) + + return migration_script + + +def render_python_code( + up_or_down_op: Union[UpgradeOps, DowngradeOps], + sqlalchemy_module_prefix: str = "sa.", + alembic_module_prefix: str = "op.", + render_as_batch: bool = False, + imports: Sequence[str] = (), + render_item: Optional[RenderItemFn] = None, + migration_context: Optional[MigrationContext] = None, + user_module_prefix: Optional[str] = None, +) -> str: + """Render Python code given an :class:`.UpgradeOps` or + :class:`.DowngradeOps` object. + + This is a convenience function that can be used to test the + autogenerate output of a user-defined :class:`.MigrationScript` structure. + + :param up_or_down_op: :class:`.UpgradeOps` or :class:`.DowngradeOps` object + :param sqlalchemy_module_prefix: module prefix for SQLAlchemy objects + :param alembic_module_prefix: module prefix for Alembic constructs + :param render_as_batch: use "batch operations" style for rendering + :param imports: sequence of import symbols to add + :param render_item: callable to render items + :param migration_context: optional :class:`.MigrationContext` + :param user_module_prefix: optional string prefix for user-defined types + + .. versionadded:: 1.11.0 + + """ + opts = { + "sqlalchemy_module_prefix": sqlalchemy_module_prefix, + "alembic_module_prefix": alembic_module_prefix, + "render_item": render_item, + "render_as_batch": render_as_batch, + "user_module_prefix": user_module_prefix, + } + + if migration_context is None: + from ..runtime.migration import MigrationContext + from sqlalchemy.engine.default import DefaultDialect + + migration_context = MigrationContext.configure( + dialect=DefaultDialect() + ) + + autogen_context = AutogenContext(migration_context, opts=opts) + autogen_context.imports = set(imports) + return render._indent( + render._render_cmd_body(up_or_down_op, autogen_context) + ) + + +def _render_migration_diffs( + context: MigrationContext, template_args: Dict[Any, Any] +) -> None: + """legacy, used by test_autogen_composition at the moment""" + + autogen_context = AutogenContext(context) + + upgrade_ops = ops.UpgradeOps([]) + compare._produce_net_changes(autogen_context, upgrade_ops) + + migration_script = ops.MigrationScript( + rev_id=None, + upgrade_ops=upgrade_ops, + downgrade_ops=upgrade_ops.reverse(), + ) + + render._render_python_into_templatevars( + autogen_context, migration_script, template_args + ) + + +class AutogenContext: + """Maintains configuration and state that's specific to an + autogenerate operation.""" + + metadata: Optional[MetaData] = None + """The :class:`~sqlalchemy.schema.MetaData` object + representing the destination. + + This object is the one that is passed within ``env.py`` + to the :paramref:`.EnvironmentContext.configure.target_metadata` + parameter. It represents the structure of :class:`.Table` and other + objects as stated in the current database model, and represents the + destination structure for the database being examined. + + While the :class:`~sqlalchemy.schema.MetaData` object is primarily + known as a collection of :class:`~sqlalchemy.schema.Table` objects, + it also has an :attr:`~sqlalchemy.schema.MetaData.info` dictionary + that may be used by end-user schemes to store additional schema-level + objects that are to be compared in custom autogeneration schemes. + + """ + + connection: Optional[Connection] = None + """The :class:`~sqlalchemy.engine.base.Connection` object currently + connected to the database backend being compared. + + This is obtained from the :attr:`.MigrationContext.bind` and is + ultimately set up in the ``env.py`` script. + + """ + + dialect: Optional[Dialect] = None + """The :class:`~sqlalchemy.engine.Dialect` object currently in use. + + This is normally obtained from the + :attr:`~sqlalchemy.engine.base.Connection.dialect` attribute. + + """ + + imports: Set[str] = None # type: ignore[assignment] + """A ``set()`` which contains string Python import directives. + + The directives are to be rendered into the ``${imports}`` section + of a script template. The set is normally empty and can be modified + within hooks such as the + :paramref:`.EnvironmentContext.configure.render_item` hook. + + .. seealso:: + + :ref:`autogen_render_types` + + """ + + migration_context: MigrationContext = None # type: ignore[assignment] + """The :class:`.MigrationContext` established by the ``env.py`` script.""" + + def __init__( + self, + migration_context: MigrationContext, + metadata: Optional[MetaData] = None, + opts: Optional[Dict[str, Any]] = None, + autogenerate: bool = True, + ) -> None: + if ( + autogenerate + and migration_context is not None + and migration_context.as_sql + ): + raise util.CommandError( + "autogenerate can't use as_sql=True as it prevents querying " + "the database for schema information" + ) + + if opts is None: + opts = migration_context.opts + + self.metadata = metadata = ( + opts.get("target_metadata", None) if metadata is None else metadata + ) + + if ( + autogenerate + and metadata is None + and migration_context is not None + and migration_context.script is not None + ): + raise util.CommandError( + "Can't proceed with --autogenerate option; environment " + "script %s does not provide " + "a MetaData object or sequence of objects to the context." + % (migration_context.script.env_py_location) + ) + + include_object = opts.get("include_object", None) + include_name = opts.get("include_name", None) + + object_filters = [] + name_filters = [] + if include_object: + object_filters.append(include_object) + if include_name: + name_filters.append(include_name) + + self._object_filters = object_filters + self._name_filters = name_filters + + self.migration_context = migration_context + if self.migration_context is not None: + self.connection = self.migration_context.bind + self.dialect = self.migration_context.dialect + + self.imports = set() + self.opts: Dict[str, Any] = opts + self._has_batch: bool = False + + @util.memoized_property + def inspector(self) -> Inspector: + if self.connection is None: + raise TypeError( + "can't return inspector as this " + "AutogenContext has no database connection" + ) + return inspect(self.connection) + + @contextlib.contextmanager + def _within_batch(self) -> Iterator[None]: + self._has_batch = True + yield + self._has_batch = False + + def run_name_filters( + self, + name: Optional[str], + type_: NameFilterType, + parent_names: NameFilterParentNames, + ) -> bool: + """Run the context's name filters and return True if the targets + should be part of the autogenerate operation. + + This method should be run for every kind of name encountered within the + reflection side of an autogenerate operation, giving the environment + the chance to filter what names should be reflected as database + objects. The filters here are produced directly via the + :paramref:`.EnvironmentContext.configure.include_name` parameter. + + """ + if "schema_name" in parent_names: + if type_ == "table": + table_name = name + else: + table_name = parent_names.get("table_name", None) + if table_name: + schema_name = parent_names["schema_name"] + if schema_name: + parent_names["schema_qualified_table_name"] = "%s.%s" % ( + schema_name, + table_name, + ) + else: + parent_names["schema_qualified_table_name"] = table_name + + for fn in self._name_filters: + if not fn(name, type_, parent_names): + return False + else: + return True + + def run_object_filters( + self, + object_: SchemaItem, + name: sqla_compat._ConstraintName, + type_: NameFilterType, + reflected: bool, + compare_to: Optional[SchemaItem], + ) -> bool: + """Run the context's object filters and return True if the targets + should be part of the autogenerate operation. + + This method should be run for every kind of object encountered within + an autogenerate operation, giving the environment the chance + to filter what objects should be included in the comparison. + The filters here are produced directly via the + :paramref:`.EnvironmentContext.configure.include_object` parameter. + + """ + for fn in self._object_filters: + if not fn(object_, name, type_, reflected, compare_to): + return False + else: + return True + + run_filters = run_object_filters + + @util.memoized_property + def sorted_tables(self) -> List[Table]: + """Return an aggregate of the :attr:`.MetaData.sorted_tables` + collection(s). + + For a sequence of :class:`.MetaData` objects, this + concatenates the :attr:`.MetaData.sorted_tables` collection + for each individual :class:`.MetaData` in the order of the + sequence. It does **not** collate the sorted tables collections. + + """ + result = [] + for m in util.to_list(self.metadata): + result.extend(m.sorted_tables) + return result + + @util.memoized_property + def table_key_to_table(self) -> Dict[str, Table]: + """Return an aggregate of the :attr:`.MetaData.tables` dictionaries. + + The :attr:`.MetaData.tables` collection is a dictionary of table key + to :class:`.Table`; this method aggregates the dictionary across + multiple :class:`.MetaData` objects into one dictionary. + + Duplicate table keys are **not** supported; if two :class:`.MetaData` + objects contain the same table key, an exception is raised. + + """ + result: Dict[str, Table] = {} + for m in util.to_list(self.metadata): + intersect = set(result).intersection(set(m.tables)) + if intersect: + raise ValueError( + "Duplicate table keys across multiple " + "MetaData objects: %s" + % (", ".join('"%s"' % key for key in sorted(intersect))) + ) + + result.update(m.tables) + return result + + +class RevisionContext: + """Maintains configuration and state that's specific to a revision + file generation operation.""" + + generated_revisions: List[MigrationScript] + process_revision_directives: Optional[ProcessRevisionDirectiveFn] + + def __init__( + self, + config: Config, + script_directory: ScriptDirectory, + command_args: Dict[str, Any], + process_revision_directives: Optional[ + ProcessRevisionDirectiveFn + ] = None, + ) -> None: + self.config = config + self.script_directory = script_directory + self.command_args = command_args + self.process_revision_directives = process_revision_directives + self.template_args = { + "config": config # Let templates use config for + # e.g. multiple databases + } + self.generated_revisions = [self._default_revision()] + + def _to_script( + self, migration_script: MigrationScript + ) -> Optional[Script]: + template_args: Dict[str, Any] = self.template_args.copy() + + if getattr(migration_script, "_needs_render", False): + autogen_context = self._last_autogen_context + + # clear out existing imports if we are doing multiple + # renders + autogen_context.imports = set() + if migration_script.imports: + autogen_context.imports.update(migration_script.imports) + render._render_python_into_templatevars( + autogen_context, migration_script, template_args + ) + + assert migration_script.rev_id is not None + return self.script_directory.generate_revision( + migration_script.rev_id, + migration_script.message, + refresh=True, + head=migration_script.head, + splice=migration_script.splice, + branch_labels=migration_script.branch_label, + version_path=migration_script.version_path, + depends_on=migration_script.depends_on, + **template_args, + ) + + def run_autogenerate( + self, rev: _GetRevArg, migration_context: MigrationContext + ) -> None: + self._run_environment(rev, migration_context, True) + + def run_no_autogenerate( + self, rev: _GetRevArg, migration_context: MigrationContext + ) -> None: + self._run_environment(rev, migration_context, False) + + def _run_environment( + self, + rev: _GetRevArg, + migration_context: MigrationContext, + autogenerate: bool, + ) -> None: + if autogenerate: + if self.command_args["sql"]: + raise util.CommandError( + "Using --sql with --autogenerate does not make any sense" + ) + if set(self.script_directory.get_revisions(rev)) != set( + self.script_directory.get_revisions("heads") + ): + raise util.CommandError("Target database is not up to date.") + + upgrade_token = migration_context.opts["upgrade_token"] + downgrade_token = migration_context.opts["downgrade_token"] + + migration_script = self.generated_revisions[-1] + if not getattr(migration_script, "_needs_render", False): + migration_script.upgrade_ops_list[-1].upgrade_token = upgrade_token + migration_script.downgrade_ops_list[ + -1 + ].downgrade_token = downgrade_token + migration_script._needs_render = True + else: + migration_script._upgrade_ops.append( + ops.UpgradeOps([], upgrade_token=upgrade_token) + ) + migration_script._downgrade_ops.append( + ops.DowngradeOps([], downgrade_token=downgrade_token) + ) + + autogen_context = AutogenContext( + migration_context, autogenerate=autogenerate + ) + self._last_autogen_context: AutogenContext = autogen_context + + if autogenerate: + compare._populate_migration_script( + autogen_context, migration_script + ) + + if self.process_revision_directives: + self.process_revision_directives( + migration_context, rev, self.generated_revisions + ) + + hook = migration_context.opts["process_revision_directives"] + if hook: + hook(migration_context, rev, self.generated_revisions) + + for migration_script in self.generated_revisions: + migration_script._needs_render = True + + def _default_revision(self) -> MigrationScript: + command_args: Dict[str, Any] = self.command_args + op = ops.MigrationScript( + rev_id=command_args["rev_id"] or util.rev_id(), + message=command_args["message"], + upgrade_ops=ops.UpgradeOps([]), + downgrade_ops=ops.DowngradeOps([]), + head=command_args["head"], + splice=command_args["splice"], + branch_label=command_args["branch_label"], + version_path=command_args["version_path"], + depends_on=command_args["depends_on"], + ) + return op + + def generate_scripts(self) -> Iterator[Optional[Script]]: + for generated_revision in self.generated_revisions: + yield self._to_script(generated_revision) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/compare.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..fcef531a544eefdc3baacff66aa5fa70229f9b58 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/compare.py @@ -0,0 +1,1329 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +import contextlib +import logging +import re +from typing import Any +from typing import cast +from typing import Dict +from typing import Iterator +from typing import Mapping +from typing import Optional +from typing import Set +from typing import Tuple +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from sqlalchemy import event +from sqlalchemy import inspect +from sqlalchemy import schema as sa_schema +from sqlalchemy import text +from sqlalchemy import types as sqltypes +from sqlalchemy.sql import expression +from sqlalchemy.sql.schema import ForeignKeyConstraint +from sqlalchemy.sql.schema import Index +from sqlalchemy.sql.schema import UniqueConstraint +from sqlalchemy.util import OrderedSet + +from .. import util +from ..ddl._autogen import is_index_sig +from ..ddl._autogen import is_uq_sig +from ..operations import ops +from ..util import sqla_compat + +if TYPE_CHECKING: + from typing import Literal + + from sqlalchemy.engine.reflection import Inspector + from sqlalchemy.sql.elements import quoted_name + from sqlalchemy.sql.elements import TextClause + from sqlalchemy.sql.schema import Column + from sqlalchemy.sql.schema import Table + + from alembic.autogenerate.api import AutogenContext + from alembic.ddl.impl import DefaultImpl + from alembic.operations.ops import AlterColumnOp + from alembic.operations.ops import MigrationScript + from alembic.operations.ops import ModifyTableOps + from alembic.operations.ops import UpgradeOps + from ..ddl._autogen import _constraint_sig + + +log = logging.getLogger(__name__) + + +def _populate_migration_script( + autogen_context: AutogenContext, migration_script: MigrationScript +) -> None: + upgrade_ops = migration_script.upgrade_ops_list[-1] + downgrade_ops = migration_script.downgrade_ops_list[-1] + + _produce_net_changes(autogen_context, upgrade_ops) + upgrade_ops.reverse_into(downgrade_ops) + + +comparators = util.Dispatcher(uselist=True) + + +def _produce_net_changes( + autogen_context: AutogenContext, upgrade_ops: UpgradeOps +) -> None: + connection = autogen_context.connection + assert connection is not None + include_schemas = autogen_context.opts.get("include_schemas", False) + + inspector: Inspector = inspect(connection) + + default_schema = connection.dialect.default_schema_name + schemas: Set[Optional[str]] + if include_schemas: + schemas = set(inspector.get_schema_names()) + # replace default schema name with None + schemas.discard("information_schema") + # replace the "default" schema with None + schemas.discard(default_schema) + schemas.add(None) + else: + schemas = {None} + + schemas = { + s for s in schemas if autogen_context.run_name_filters(s, "schema", {}) + } + + assert autogen_context.dialect is not None + comparators.dispatch("schema", autogen_context.dialect.name)( + autogen_context, upgrade_ops, schemas + ) + + +@comparators.dispatch_for("schema") +def _autogen_for_tables( + autogen_context: AutogenContext, + upgrade_ops: UpgradeOps, + schemas: Union[Set[None], Set[Optional[str]]], +) -> None: + inspector = autogen_context.inspector + + conn_table_names: Set[Tuple[Optional[str], str]] = set() + + version_table_schema = ( + autogen_context.migration_context.version_table_schema + ) + version_table = autogen_context.migration_context.version_table + + for schema_name in schemas: + tables = set(inspector.get_table_names(schema=schema_name)) + if schema_name == version_table_schema: + tables = tables.difference( + [autogen_context.migration_context.version_table] + ) + + conn_table_names.update( + (schema_name, tname) + for tname in tables + if autogen_context.run_name_filters( + tname, "table", {"schema_name": schema_name} + ) + ) + + metadata_table_names = OrderedSet( + [(table.schema, table.name) for table in autogen_context.sorted_tables] + ).difference([(version_table_schema, version_table)]) + + _compare_tables( + conn_table_names, + metadata_table_names, + inspector, + upgrade_ops, + autogen_context, + ) + + +def _compare_tables( + conn_table_names: set, + metadata_table_names: set, + inspector: Inspector, + upgrade_ops: UpgradeOps, + autogen_context: AutogenContext, +) -> None: + default_schema = inspector.bind.dialect.default_schema_name + + # tables coming from the connection will not have "schema" + # set if it matches default_schema_name; so we need a list + # of table names from local metadata that also have "None" if schema + # == default_schema_name. Most setups will be like this anyway but + # some are not (see #170) + metadata_table_names_no_dflt_schema = OrderedSet( + [ + (schema if schema != default_schema else None, tname) + for schema, tname in metadata_table_names + ] + ) + + # to adjust for the MetaData collection storing the tables either + # as "schemaname.tablename" or just "tablename", create a new lookup + # which will match the "non-default-schema" keys to the Table object. + tname_to_table = { + no_dflt_schema: autogen_context.table_key_to_table[ + sa_schema._get_table_key(tname, schema) + ] + for no_dflt_schema, (schema, tname) in zip( + metadata_table_names_no_dflt_schema, metadata_table_names + ) + } + metadata_table_names = metadata_table_names_no_dflt_schema + + for s, tname in metadata_table_names.difference(conn_table_names): + name = "%s.%s" % (s, tname) if s else tname + metadata_table = tname_to_table[(s, tname)] + if autogen_context.run_object_filters( + metadata_table, tname, "table", False, None + ): + upgrade_ops.ops.append( + ops.CreateTableOp.from_table(metadata_table) + ) + log.info("Detected added table %r", name) + modify_table_ops = ops.ModifyTableOps(tname, [], schema=s) + + comparators.dispatch("table")( + autogen_context, + modify_table_ops, + s, + tname, + None, + metadata_table, + ) + if not modify_table_ops.is_empty(): + upgrade_ops.ops.append(modify_table_ops) + + removal_metadata = sa_schema.MetaData() + for s, tname in conn_table_names.difference(metadata_table_names): + name = sa_schema._get_table_key(tname, s) + exists = name in removal_metadata.tables + t = sa_schema.Table(tname, removal_metadata, schema=s) + + if not exists: + event.listen( + t, + "column_reflect", + # fmt: off + autogen_context.migration_context.impl. + _compat_autogen_column_reflect + (inspector), + # fmt: on + ) + sqla_compat._reflect_table(inspector, t) + if autogen_context.run_object_filters(t, tname, "table", True, None): + modify_table_ops = ops.ModifyTableOps(tname, [], schema=s) + + comparators.dispatch("table")( + autogen_context, modify_table_ops, s, tname, t, None + ) + if not modify_table_ops.is_empty(): + upgrade_ops.ops.append(modify_table_ops) + + upgrade_ops.ops.append(ops.DropTableOp.from_table(t)) + log.info("Detected removed table %r", name) + + existing_tables = conn_table_names.intersection(metadata_table_names) + + existing_metadata = sa_schema.MetaData() + conn_column_info = {} + for s, tname in existing_tables: + name = sa_schema._get_table_key(tname, s) + exists = name in existing_metadata.tables + t = sa_schema.Table(tname, existing_metadata, schema=s) + if not exists: + event.listen( + t, + "column_reflect", + # fmt: off + autogen_context.migration_context.impl. + _compat_autogen_column_reflect(inspector), + # fmt: on + ) + sqla_compat._reflect_table(inspector, t) + conn_column_info[(s, tname)] = t + + for s, tname in sorted(existing_tables, key=lambda x: (x[0] or "", x[1])): + s = s or None + name = "%s.%s" % (s, tname) if s else tname + metadata_table = tname_to_table[(s, tname)] + conn_table = existing_metadata.tables[name] + + if autogen_context.run_object_filters( + metadata_table, tname, "table", False, conn_table + ): + modify_table_ops = ops.ModifyTableOps(tname, [], schema=s) + with _compare_columns( + s, + tname, + conn_table, + metadata_table, + modify_table_ops, + autogen_context, + inspector, + ): + comparators.dispatch("table")( + autogen_context, + modify_table_ops, + s, + tname, + conn_table, + metadata_table, + ) + + if not modify_table_ops.is_empty(): + upgrade_ops.ops.append(modify_table_ops) + + +_IndexColumnSortingOps: Mapping[str, Any] = util.immutabledict( + { + "asc": expression.asc, + "desc": expression.desc, + "nulls_first": expression.nullsfirst, + "nulls_last": expression.nullslast, + "nullsfirst": expression.nullsfirst, # 1_3 name + "nullslast": expression.nullslast, # 1_3 name + } +) + + +def _make_index( + impl: DefaultImpl, params: Dict[str, Any], conn_table: Table +) -> Optional[Index]: + exprs: list[Union[Column[Any], TextClause]] = [] + sorting = params.get("column_sorting") + + for num, col_name in enumerate(params["column_names"]): + item: Union[Column[Any], TextClause] + if col_name is None: + assert "expressions" in params + name = params["expressions"][num] + item = text(name) + else: + name = col_name + item = conn_table.c[col_name] + if sorting and name in sorting: + for operator in sorting[name]: + if operator in _IndexColumnSortingOps: + item = _IndexColumnSortingOps[operator](item) + exprs.append(item) + ix = sa_schema.Index( + params["name"], + *exprs, + unique=params["unique"], + _table=conn_table, + **impl.adjust_reflected_dialect_options(params, "index"), + ) + if "duplicates_constraint" in params: + ix.info["duplicates_constraint"] = params["duplicates_constraint"] + return ix + + +def _make_unique_constraint( + impl: DefaultImpl, params: Dict[str, Any], conn_table: Table +) -> UniqueConstraint: + uq = sa_schema.UniqueConstraint( + *[conn_table.c[cname] for cname in params["column_names"]], + name=params["name"], + **impl.adjust_reflected_dialect_options(params, "unique_constraint"), + ) + if "duplicates_index" in params: + uq.info["duplicates_index"] = params["duplicates_index"] + + return uq + + +def _make_foreign_key( + params: Dict[str, Any], conn_table: Table +) -> ForeignKeyConstraint: + tname = params["referred_table"] + if params["referred_schema"]: + tname = "%s.%s" % (params["referred_schema"], tname) + + options = params.get("options", {}) + + const = sa_schema.ForeignKeyConstraint( + [conn_table.c[cname] for cname in params["constrained_columns"]], + ["%s.%s" % (tname, n) for n in params["referred_columns"]], + onupdate=options.get("onupdate"), + ondelete=options.get("ondelete"), + deferrable=options.get("deferrable"), + initially=options.get("initially"), + name=params["name"], + ) + # needed by 0.7 + conn_table.append_constraint(const) + return const + + +@contextlib.contextmanager +def _compare_columns( + schema: Optional[str], + tname: Union[quoted_name, str], + conn_table: Table, + metadata_table: Table, + modify_table_ops: ModifyTableOps, + autogen_context: AutogenContext, + inspector: Inspector, +) -> Iterator[None]: + name = "%s.%s" % (schema, tname) if schema else tname + metadata_col_names = OrderedSet( + c.name for c in metadata_table.c if not c.system + ) + metadata_cols_by_name = { + c.name: c for c in metadata_table.c if not c.system + } + + conn_col_names = { + c.name: c + for c in conn_table.c + if autogen_context.run_name_filters( + c.name, "column", {"table_name": tname, "schema_name": schema} + ) + } + + for cname in metadata_col_names.difference(conn_col_names): + if autogen_context.run_object_filters( + metadata_cols_by_name[cname], cname, "column", False, None + ): + modify_table_ops.ops.append( + ops.AddColumnOp.from_column_and_tablename( + schema, tname, metadata_cols_by_name[cname] + ) + ) + log.info("Detected added column '%s.%s'", name, cname) + + for colname in metadata_col_names.intersection(conn_col_names): + metadata_col = metadata_cols_by_name[colname] + conn_col = conn_table.c[colname] + if not autogen_context.run_object_filters( + metadata_col, colname, "column", False, conn_col + ): + continue + alter_column_op = ops.AlterColumnOp(tname, colname, schema=schema) + + comparators.dispatch("column")( + autogen_context, + alter_column_op, + schema, + tname, + colname, + conn_col, + metadata_col, + ) + + if alter_column_op.has_changes(): + modify_table_ops.ops.append(alter_column_op) + + yield + + for cname in set(conn_col_names).difference(metadata_col_names): + if autogen_context.run_object_filters( + conn_table.c[cname], cname, "column", True, None + ): + modify_table_ops.ops.append( + ops.DropColumnOp.from_column_and_tablename( + schema, tname, conn_table.c[cname] + ) + ) + log.info("Detected removed column '%s.%s'", name, cname) + + +_C = TypeVar("_C", bound=Union[UniqueConstraint, ForeignKeyConstraint, Index]) + + +@comparators.dispatch_for("table") +def _compare_indexes_and_uniques( + autogen_context: AutogenContext, + modify_ops: ModifyTableOps, + schema: Optional[str], + tname: Union[quoted_name, str], + conn_table: Optional[Table], + metadata_table: Optional[Table], +) -> None: + inspector = autogen_context.inspector + is_create_table = conn_table is None + is_drop_table = metadata_table is None + impl = autogen_context.migration_context.impl + + # 1a. get raw indexes and unique constraints from metadata ... + if metadata_table is not None: + metadata_unique_constraints = { + uq + for uq in metadata_table.constraints + if isinstance(uq, sa_schema.UniqueConstraint) + } + metadata_indexes = set(metadata_table.indexes) + else: + metadata_unique_constraints = set() + metadata_indexes = set() + + conn_uniques = conn_indexes = frozenset() # type:ignore[var-annotated] + + supports_unique_constraints = False + + unique_constraints_duplicate_unique_indexes = False + + if conn_table is not None: + # 1b. ... and from connection, if the table exists + try: + conn_uniques = inspector.get_unique_constraints( # type:ignore[assignment] # noqa + tname, schema=schema + ) + supports_unique_constraints = True + except NotImplementedError: + pass + except TypeError: + # number of arguments is off for the base + # method in SQLAlchemy due to the cache decorator + # not being present + pass + else: + conn_uniques = [ # type:ignore[assignment] + uq + for uq in conn_uniques + if autogen_context.run_name_filters( + uq["name"], + "unique_constraint", + {"table_name": tname, "schema_name": schema}, + ) + ] + for uq in conn_uniques: + if uq.get("duplicates_index"): + unique_constraints_duplicate_unique_indexes = True + try: + conn_indexes = inspector.get_indexes( # type:ignore[assignment] + tname, schema=schema + ) + except NotImplementedError: + pass + else: + conn_indexes = [ # type:ignore[assignment] + ix + for ix in conn_indexes + if autogen_context.run_name_filters( + ix["name"], + "index", + {"table_name": tname, "schema_name": schema}, + ) + ] + + # 2. convert conn-level objects from raw inspector records + # into schema objects + if is_drop_table: + # for DROP TABLE uniques are inline, don't need them + conn_uniques = set() # type:ignore[assignment] + else: + conn_uniques = { # type:ignore[assignment] + _make_unique_constraint(impl, uq_def, conn_table) + for uq_def in conn_uniques + } + + conn_indexes = { # type:ignore[assignment] + index + for index in ( + _make_index(impl, ix, conn_table) for ix in conn_indexes + ) + if index is not None + } + + # 2a. if the dialect dupes unique indexes as unique constraints + # (mysql and oracle), correct for that + + if unique_constraints_duplicate_unique_indexes: + _correct_for_uq_duplicates_uix( + conn_uniques, + conn_indexes, + metadata_unique_constraints, + metadata_indexes, + autogen_context.dialect, + impl, + ) + + # 3. give the dialect a chance to omit indexes and constraints that + # we know are either added implicitly by the DB or that the DB + # can't accurately report on + impl.correct_for_autogen_constraints( + conn_uniques, # type: ignore[arg-type] + conn_indexes, # type: ignore[arg-type] + metadata_unique_constraints, + metadata_indexes, + ) + + # 4. organize the constraints into "signature" collections, the + # _constraint_sig() objects provide a consistent facade over both + # Index and UniqueConstraint so we can easily work with them + # interchangeably + metadata_unique_constraints_sig = { + impl._create_metadata_constraint_sig(uq) + for uq in metadata_unique_constraints + } + + metadata_indexes_sig = { + impl._create_metadata_constraint_sig(ix) for ix in metadata_indexes + } + + conn_unique_constraints = { + impl._create_reflected_constraint_sig(uq) for uq in conn_uniques + } + + conn_indexes_sig = { + impl._create_reflected_constraint_sig(ix) for ix in conn_indexes + } + + # 5. index things by name, for those objects that have names + metadata_names = { + cast(str, c.md_name_to_sql_name(autogen_context)): c + for c in metadata_unique_constraints_sig.union(metadata_indexes_sig) + if c.is_named + } + + conn_uniques_by_name: Dict[sqla_compat._ConstraintName, _constraint_sig] + conn_indexes_by_name: Dict[sqla_compat._ConstraintName, _constraint_sig] + + conn_uniques_by_name = {c.name: c for c in conn_unique_constraints} + conn_indexes_by_name = {c.name: c for c in conn_indexes_sig} + conn_names = { + c.name: c + for c in conn_unique_constraints.union(conn_indexes_sig) + if sqla_compat.constraint_name_string(c.name) + } + + doubled_constraints = { + name: (conn_uniques_by_name[name], conn_indexes_by_name[name]) + for name in set(conn_uniques_by_name).intersection( + conn_indexes_by_name + ) + } + + # 6. index things by "column signature", to help with unnamed unique + # constraints. + conn_uniques_by_sig = {uq.unnamed: uq for uq in conn_unique_constraints} + metadata_uniques_by_sig = { + uq.unnamed: uq for uq in metadata_unique_constraints_sig + } + unnamed_metadata_uniques = { + uq.unnamed: uq + for uq in metadata_unique_constraints_sig + if not sqla_compat._constraint_is_named( + uq.const, autogen_context.dialect + ) + } + + # assumptions: + # 1. a unique constraint or an index from the connection *always* + # has a name. + # 2. an index on the metadata side *always* has a name. + # 3. a unique constraint on the metadata side *might* have a name. + # 4. The backend may double up indexes as unique constraints and + # vice versa (e.g. MySQL, Postgresql) + + def obj_added(obj: _constraint_sig): + if is_index_sig(obj): + if autogen_context.run_object_filters( + obj.const, obj.name, "index", False, None + ): + modify_ops.ops.append(ops.CreateIndexOp.from_index(obj.const)) + log.info( + "Detected added index '%r' on '%s'", + obj.name, + obj.column_names, + ) + elif is_uq_sig(obj): + if not supports_unique_constraints: + # can't report unique indexes as added if we don't + # detect them + return + if is_create_table or is_drop_table: + # unique constraints are created inline with table defs + return + if autogen_context.run_object_filters( + obj.const, obj.name, "unique_constraint", False, None + ): + modify_ops.ops.append( + ops.AddConstraintOp.from_constraint(obj.const) + ) + log.info( + "Detected added unique constraint %r on '%s'", + obj.name, + obj.column_names, + ) + else: + assert False + + def obj_removed(obj: _constraint_sig): + if is_index_sig(obj): + if obj.is_unique and not supports_unique_constraints: + # many databases double up unique constraints + # as unique indexes. without that list we can't + # be sure what we're doing here + return + + if autogen_context.run_object_filters( + obj.const, obj.name, "index", True, None + ): + modify_ops.ops.append(ops.DropIndexOp.from_index(obj.const)) + log.info("Detected removed index %r on %r", obj.name, tname) + elif is_uq_sig(obj): + if is_create_table or is_drop_table: + # if the whole table is being dropped, we don't need to + # consider unique constraint separately + return + if autogen_context.run_object_filters( + obj.const, obj.name, "unique_constraint", True, None + ): + modify_ops.ops.append( + ops.DropConstraintOp.from_constraint(obj.const) + ) + log.info( + "Detected removed unique constraint %r on %r", + obj.name, + tname, + ) + else: + assert False + + def obj_changed( + old: _constraint_sig, + new: _constraint_sig, + msg: str, + ): + if is_index_sig(old): + assert is_index_sig(new) + + if autogen_context.run_object_filters( + new.const, new.name, "index", False, old.const + ): + log.info( + "Detected changed index %r on %r: %s", old.name, tname, msg + ) + modify_ops.ops.append(ops.DropIndexOp.from_index(old.const)) + modify_ops.ops.append(ops.CreateIndexOp.from_index(new.const)) + elif is_uq_sig(old): + assert is_uq_sig(new) + + if autogen_context.run_object_filters( + new.const, new.name, "unique_constraint", False, old.const + ): + log.info( + "Detected changed unique constraint %r on %r: %s", + old.name, + tname, + msg, + ) + modify_ops.ops.append( + ops.DropConstraintOp.from_constraint(old.const) + ) + modify_ops.ops.append( + ops.AddConstraintOp.from_constraint(new.const) + ) + else: + assert False + + for removed_name in sorted(set(conn_names).difference(metadata_names)): + conn_obj = conn_names[removed_name] + if ( + is_uq_sig(conn_obj) + and conn_obj.unnamed in unnamed_metadata_uniques + ): + continue + elif removed_name in doubled_constraints: + conn_uq, conn_idx = doubled_constraints[removed_name] + if ( + all( + conn_idx.unnamed != meta_idx.unnamed + for meta_idx in metadata_indexes_sig + ) + and conn_uq.unnamed not in metadata_uniques_by_sig + ): + obj_removed(conn_uq) + obj_removed(conn_idx) + else: + obj_removed(conn_obj) + + for existing_name in sorted(set(metadata_names).intersection(conn_names)): + metadata_obj = metadata_names[existing_name] + + if existing_name in doubled_constraints: + conn_uq, conn_idx = doubled_constraints[existing_name] + if is_index_sig(metadata_obj): + conn_obj = conn_idx + else: + conn_obj = conn_uq + else: + conn_obj = conn_names[existing_name] + + if type(conn_obj) != type(metadata_obj): + obj_removed(conn_obj) + obj_added(metadata_obj) + else: + comparison = metadata_obj.compare_to_reflected(conn_obj) + + if comparison.is_different: + # constraint are different + obj_changed(conn_obj, metadata_obj, comparison.message) + elif comparison.is_skip: + # constraint cannot be compared, skip them + thing = ( + "index" if is_index_sig(conn_obj) else "unique constraint" + ) + log.info( + "Cannot compare %s %r, assuming equal and skipping. %s", + thing, + conn_obj.name, + comparison.message, + ) + else: + # constraint are equal + assert comparison.is_equal + + for added_name in sorted(set(metadata_names).difference(conn_names)): + obj = metadata_names[added_name] + obj_added(obj) + + for uq_sig in unnamed_metadata_uniques: + if uq_sig not in conn_uniques_by_sig: + obj_added(unnamed_metadata_uniques[uq_sig]) + + +def _correct_for_uq_duplicates_uix( + conn_unique_constraints, + conn_indexes, + metadata_unique_constraints, + metadata_indexes, + dialect, + impl, +): + # dedupe unique indexes vs. constraints, since MySQL / Oracle + # doesn't really have unique constraints as a separate construct. + # but look in the metadata and try to maintain constructs + # that already seem to be defined one way or the other + # on that side. This logic was formerly local to MySQL dialect, + # generalized to Oracle and others. See #276 + + # resolve final rendered name for unique constraints defined in the + # metadata. this includes truncation of long names. naming convention + # names currently should already be set as cons.name, however leave this + # to the sqla_compat to decide. + metadata_cons_names = [ + (sqla_compat._get_constraint_final_name(cons, dialect), cons) + for cons in metadata_unique_constraints + ] + + metadata_uq_names = { + name for name, cons in metadata_cons_names if name is not None + } + + unnamed_metadata_uqs = { + impl._create_metadata_constraint_sig(cons).unnamed + for name, cons in metadata_cons_names + if name is None + } + + metadata_ix_names = { + sqla_compat._get_constraint_final_name(cons, dialect) + for cons in metadata_indexes + if cons.unique + } + + # for reflection side, names are in their final database form + # already since they're from the database + conn_ix_names = {cons.name: cons for cons in conn_indexes if cons.unique} + + uqs_dupe_indexes = { + cons.name: cons + for cons in conn_unique_constraints + if cons.info["duplicates_index"] + } + + for overlap in uqs_dupe_indexes: + if overlap not in metadata_uq_names: + if ( + impl._create_reflected_constraint_sig( + uqs_dupe_indexes[overlap] + ).unnamed + not in unnamed_metadata_uqs + ): + conn_unique_constraints.discard(uqs_dupe_indexes[overlap]) + elif overlap not in metadata_ix_names: + conn_indexes.discard(conn_ix_names[overlap]) + + +@comparators.dispatch_for("column") +def _compare_nullable( + autogen_context: AutogenContext, + alter_column_op: AlterColumnOp, + schema: Optional[str], + tname: Union[quoted_name, str], + cname: Union[quoted_name, str], + conn_col: Column[Any], + metadata_col: Column[Any], +) -> None: + metadata_col_nullable = metadata_col.nullable + conn_col_nullable = conn_col.nullable + alter_column_op.existing_nullable = conn_col_nullable + + if conn_col_nullable is not metadata_col_nullable: + if ( + sqla_compat._server_default_is_computed( + metadata_col.server_default, conn_col.server_default + ) + and sqla_compat._nullability_might_be_unset(metadata_col) + or ( + sqla_compat._server_default_is_identity( + metadata_col.server_default, conn_col.server_default + ) + ) + ): + log.info( + "Ignoring nullable change on identity column '%s.%s'", + tname, + cname, + ) + else: + alter_column_op.modify_nullable = metadata_col_nullable + log.info( + "Detected %s on column '%s.%s'", + "NULL" if metadata_col_nullable else "NOT NULL", + tname, + cname, + ) + + +@comparators.dispatch_for("column") +def _setup_autoincrement( + autogen_context: AutogenContext, + alter_column_op: AlterColumnOp, + schema: Optional[str], + tname: Union[quoted_name, str], + cname: quoted_name, + conn_col: Column[Any], + metadata_col: Column[Any], +) -> None: + if metadata_col.table._autoincrement_column is metadata_col: + alter_column_op.kw["autoincrement"] = True + elif metadata_col.autoincrement is True: + alter_column_op.kw["autoincrement"] = True + elif metadata_col.autoincrement is False: + alter_column_op.kw["autoincrement"] = False + + +@comparators.dispatch_for("column") +def _compare_type( + autogen_context: AutogenContext, + alter_column_op: AlterColumnOp, + schema: Optional[str], + tname: Union[quoted_name, str], + cname: Union[quoted_name, str], + conn_col: Column[Any], + metadata_col: Column[Any], +) -> None: + conn_type = conn_col.type + alter_column_op.existing_type = conn_type + metadata_type = metadata_col.type + if conn_type._type_affinity is sqltypes.NullType: + log.info( + "Couldn't determine database type " "for column '%s.%s'", + tname, + cname, + ) + return + if metadata_type._type_affinity is sqltypes.NullType: + log.info( + "Column '%s.%s' has no type within " "the model; can't compare", + tname, + cname, + ) + return + + isdiff = autogen_context.migration_context._compare_type( + conn_col, metadata_col + ) + + if isdiff: + alter_column_op.modify_type = metadata_type + log.info( + "Detected type change from %r to %r on '%s.%s'", + conn_type, + metadata_type, + tname, + cname, + ) + + +def _render_server_default_for_compare( + metadata_default: Optional[Any], autogen_context: AutogenContext +) -> Optional[str]: + if isinstance(metadata_default, sa_schema.DefaultClause): + if isinstance(metadata_default.arg, str): + metadata_default = metadata_default.arg + else: + metadata_default = str( + metadata_default.arg.compile( + dialect=autogen_context.dialect, + compile_kwargs={"literal_binds": True}, + ) + ) + if isinstance(metadata_default, str): + return metadata_default + else: + return None + + +def _normalize_computed_default(sqltext: str) -> str: + """we want to warn if a computed sql expression has changed. however + we don't want false positives and the warning is not that critical. + so filter out most forms of variability from the SQL text. + + """ + + return re.sub(r"[ \(\)'\"`\[\]]", "", sqltext).lower() + + +def _compare_computed_default( + autogen_context: AutogenContext, + alter_column_op: AlterColumnOp, + schema: Optional[str], + tname: str, + cname: str, + conn_col: Column[Any], + metadata_col: Column[Any], +) -> None: + rendered_metadata_default = str( + cast(sa_schema.Computed, metadata_col.server_default).sqltext.compile( + dialect=autogen_context.dialect, + compile_kwargs={"literal_binds": True}, + ) + ) + + # since we cannot change computed columns, we do only a crude comparison + # here where we try to eliminate syntactical differences in order to + # get a minimal comparison just to emit a warning. + + rendered_metadata_default = _normalize_computed_default( + rendered_metadata_default + ) + + if isinstance(conn_col.server_default, sa_schema.Computed): + rendered_conn_default = str( + conn_col.server_default.sqltext.compile( + dialect=autogen_context.dialect, + compile_kwargs={"literal_binds": True}, + ) + ) + if rendered_conn_default is None: + rendered_conn_default = "" + else: + rendered_conn_default = _normalize_computed_default( + rendered_conn_default + ) + else: + rendered_conn_default = "" + + if rendered_metadata_default != rendered_conn_default: + _warn_computed_not_supported(tname, cname) + + +def _warn_computed_not_supported(tname: str, cname: str) -> None: + util.warn("Computed default on %s.%s cannot be modified" % (tname, cname)) + + +def _compare_identity_default( + autogen_context, + alter_column_op, + schema, + tname, + cname, + conn_col, + metadata_col, +): + impl = autogen_context.migration_context.impl + diff, ignored_attr, is_alter = impl._compare_identity_default( + metadata_col.server_default, conn_col.server_default + ) + + return diff, is_alter + + +@comparators.dispatch_for("column") +def _compare_server_default( + autogen_context: AutogenContext, + alter_column_op: AlterColumnOp, + schema: Optional[str], + tname: Union[quoted_name, str], + cname: Union[quoted_name, str], + conn_col: Column[Any], + metadata_col: Column[Any], +) -> Optional[bool]: + metadata_default = metadata_col.server_default + conn_col_default = conn_col.server_default + if conn_col_default is None and metadata_default is None: + return False + + if sqla_compat._server_default_is_computed(metadata_default): + # return False in case of a computed column as the server + # default. Note that DDL for adding or removing "GENERATED AS" from + # an existing column is not currently known for any backend. + # Once SQLAlchemy can reflect "GENERATED" as the "computed" element, + # we would also want to ignore and/or warn for changes vs. the + # metadata (or support backend specific DDL if applicable). + if not sqla_compat.has_computed_reflection: + return False + + else: + return ( + _compare_computed_default( # type:ignore[func-returns-value] + autogen_context, + alter_column_op, + schema, + tname, + cname, + conn_col, + metadata_col, + ) + ) + if sqla_compat._server_default_is_computed(conn_col_default): + _warn_computed_not_supported(tname, cname) + return False + + if sqla_compat._server_default_is_identity( + metadata_default, conn_col_default + ): + alter_column_op.existing_server_default = conn_col_default + diff, is_alter = _compare_identity_default( + autogen_context, + alter_column_op, + schema, + tname, + cname, + conn_col, + metadata_col, + ) + if is_alter: + alter_column_op.modify_server_default = metadata_default + if diff: + log.info( + "Detected server default on column '%s.%s': " + "identity options attributes %s", + tname, + cname, + sorted(diff), + ) + else: + rendered_metadata_default = _render_server_default_for_compare( + metadata_default, autogen_context + ) + + rendered_conn_default = ( + cast(Any, conn_col_default).arg.text if conn_col_default else None + ) + + alter_column_op.existing_server_default = conn_col_default + + is_diff = autogen_context.migration_context._compare_server_default( + conn_col, + metadata_col, + rendered_metadata_default, + rendered_conn_default, + ) + if is_diff: + alter_column_op.modify_server_default = metadata_default + log.info("Detected server default on column '%s.%s'", tname, cname) + + return None + + +@comparators.dispatch_for("column") +def _compare_column_comment( + autogen_context: AutogenContext, + alter_column_op: AlterColumnOp, + schema: Optional[str], + tname: Union[quoted_name, str], + cname: quoted_name, + conn_col: Column[Any], + metadata_col: Column[Any], +) -> Optional[Literal[False]]: + assert autogen_context.dialect is not None + if not autogen_context.dialect.supports_comments: + return None + + metadata_comment = metadata_col.comment + conn_col_comment = conn_col.comment + if conn_col_comment is None and metadata_comment is None: + return False + + alter_column_op.existing_comment = conn_col_comment + + if conn_col_comment != metadata_comment: + alter_column_op.modify_comment = metadata_comment + log.info("Detected column comment '%s.%s'", tname, cname) + + return None + + +@comparators.dispatch_for("table") +def _compare_foreign_keys( + autogen_context: AutogenContext, + modify_table_ops: ModifyTableOps, + schema: Optional[str], + tname: Union[quoted_name, str], + conn_table: Table, + metadata_table: Table, +) -> None: + # if we're doing CREATE TABLE, all FKs are created + # inline within the table def + if conn_table is None or metadata_table is None: + return + + inspector = autogen_context.inspector + metadata_fks = { + fk + for fk in metadata_table.constraints + if isinstance(fk, sa_schema.ForeignKeyConstraint) + } + + conn_fks_list = [ + fk + for fk in inspector.get_foreign_keys(tname, schema=schema) + if autogen_context.run_name_filters( + fk["name"], + "foreign_key_constraint", + {"table_name": tname, "schema_name": schema}, + ) + ] + + conn_fks = { + _make_foreign_key(const, conn_table) # type: ignore[arg-type] + for const in conn_fks_list + } + + impl = autogen_context.migration_context.impl + + # give the dialect a chance to correct the FKs to match more + # closely + autogen_context.migration_context.impl.correct_for_autogen_foreignkeys( + conn_fks, metadata_fks + ) + + metadata_fks_sig = { + impl._create_metadata_constraint_sig(fk) for fk in metadata_fks + } + + conn_fks_sig = { + impl._create_reflected_constraint_sig(fk) for fk in conn_fks + } + + # check if reflected FKs include options, indicating the backend + # can reflect FK options + if conn_fks_list and "options" in conn_fks_list[0]: + conn_fks_by_sig = {c.unnamed: c for c in conn_fks_sig} + metadata_fks_by_sig = {c.unnamed: c for c in metadata_fks_sig} + else: + # otherwise compare by sig without options added + conn_fks_by_sig = {c.unnamed_no_options: c for c in conn_fks_sig} + metadata_fks_by_sig = { + c.unnamed_no_options: c for c in metadata_fks_sig + } + + metadata_fks_by_name = { + c.name: c for c in metadata_fks_sig if c.name is not None + } + conn_fks_by_name = {c.name: c for c in conn_fks_sig if c.name is not None} + + def _add_fk(obj, compare_to): + if autogen_context.run_object_filters( + obj.const, obj.name, "foreign_key_constraint", False, compare_to + ): + modify_table_ops.ops.append( + ops.CreateForeignKeyOp.from_constraint(const.const) # type: ignore[has-type] # noqa: E501 + ) + + log.info( + "Detected added foreign key (%s)(%s) on table %s%s", + ", ".join(obj.source_columns), + ", ".join(obj.target_columns), + "%s." % obj.source_schema if obj.source_schema else "", + obj.source_table, + ) + + def _remove_fk(obj, compare_to): + if autogen_context.run_object_filters( + obj.const, obj.name, "foreign_key_constraint", True, compare_to + ): + modify_table_ops.ops.append( + ops.DropConstraintOp.from_constraint(obj.const) + ) + log.info( + "Detected removed foreign key (%s)(%s) on table %s%s", + ", ".join(obj.source_columns), + ", ".join(obj.target_columns), + "%s." % obj.source_schema if obj.source_schema else "", + obj.source_table, + ) + + # so far it appears we don't need to do this by name at all. + # SQLite doesn't preserve constraint names anyway + + for removed_sig in set(conn_fks_by_sig).difference(metadata_fks_by_sig): + const = conn_fks_by_sig[removed_sig] + if removed_sig not in metadata_fks_by_sig: + compare_to = ( + metadata_fks_by_name[const.name].const + if const.name in metadata_fks_by_name + else None + ) + _remove_fk(const, compare_to) + + for added_sig in set(metadata_fks_by_sig).difference(conn_fks_by_sig): + const = metadata_fks_by_sig[added_sig] + if added_sig not in conn_fks_by_sig: + compare_to = ( + conn_fks_by_name[const.name].const + if const.name in conn_fks_by_name + else None + ) + _add_fk(const, compare_to) + + +@comparators.dispatch_for("table") +def _compare_table_comment( + autogen_context: AutogenContext, + modify_table_ops: ModifyTableOps, + schema: Optional[str], + tname: Union[quoted_name, str], + conn_table: Optional[Table], + metadata_table: Optional[Table], +) -> None: + assert autogen_context.dialect is not None + if not autogen_context.dialect.supports_comments: + return + + # if we're doing CREATE TABLE, comments will be created inline + # with the create_table op. + if conn_table is None or metadata_table is None: + return + + if conn_table.comment is None and metadata_table.comment is None: + return + + if metadata_table.comment is None and conn_table.comment is not None: + modify_table_ops.ops.append( + ops.DropTableCommentOp( + tname, existing_comment=conn_table.comment, schema=schema + ) + ) + elif metadata_table.comment != conn_table.comment: + modify_table_ops.ops.append( + ops.CreateTableCommentOp( + tname, + metadata_table.comment, + existing_comment=conn_table.comment, + schema=schema, + ) + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/render.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/render.py new file mode 100644 index 0000000000000000000000000000000000000000..317a6dbed9cf6eb6514d67a82ee3ee853c22254b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/render.py @@ -0,0 +1,1097 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +from io import StringIO +import re +from typing import Any +from typing import cast +from typing import Dict +from typing import List +from typing import Optional +from typing import Tuple +from typing import TYPE_CHECKING +from typing import Union + +from mako.pygen import PythonPrinter +from sqlalchemy import schema as sa_schema +from sqlalchemy import sql +from sqlalchemy import types as sqltypes +from sqlalchemy.sql.elements import conv +from sqlalchemy.sql.elements import quoted_name + +from .. import util +from ..operations import ops +from ..util import sqla_compat + +if TYPE_CHECKING: + from typing import Literal + + from sqlalchemy.sql.base import DialectKWArgs + from sqlalchemy.sql.elements import ColumnElement + from sqlalchemy.sql.elements import TextClause + from sqlalchemy.sql.schema import CheckConstraint + from sqlalchemy.sql.schema import Column + from sqlalchemy.sql.schema import Constraint + from sqlalchemy.sql.schema import FetchedValue + from sqlalchemy.sql.schema import ForeignKey + from sqlalchemy.sql.schema import ForeignKeyConstraint + from sqlalchemy.sql.schema import Index + from sqlalchemy.sql.schema import MetaData + from sqlalchemy.sql.schema import PrimaryKeyConstraint + from sqlalchemy.sql.schema import UniqueConstraint + from sqlalchemy.sql.sqltypes import ARRAY + from sqlalchemy.sql.type_api import TypeEngine + + from alembic.autogenerate.api import AutogenContext + from alembic.config import Config + from alembic.operations.ops import MigrationScript + from alembic.operations.ops import ModifyTableOps + from alembic.util.sqla_compat import Computed + from alembic.util.sqla_compat import Identity + + +MAX_PYTHON_ARGS = 255 + + +def _render_gen_name( + autogen_context: AutogenContext, + name: sqla_compat._ConstraintName, +) -> Optional[Union[quoted_name, str, _f_name]]: + if isinstance(name, conv): + return _f_name(_alembic_autogenerate_prefix(autogen_context), name) + else: + return sqla_compat.constraint_name_or_none(name) + + +def _indent(text: str) -> str: + text = re.compile(r"^", re.M).sub(" ", text).strip() + text = re.compile(r" +$", re.M).sub("", text) + return text + + +def _render_python_into_templatevars( + autogen_context: AutogenContext, + migration_script: MigrationScript, + template_args: Dict[str, Union[str, Config]], +) -> None: + imports = autogen_context.imports + + for upgrade_ops, downgrade_ops in zip( + migration_script.upgrade_ops_list, migration_script.downgrade_ops_list + ): + template_args[upgrade_ops.upgrade_token] = _indent( + _render_cmd_body(upgrade_ops, autogen_context) + ) + template_args[downgrade_ops.downgrade_token] = _indent( + _render_cmd_body(downgrade_ops, autogen_context) + ) + template_args["imports"] = "\n".join(sorted(imports)) + + +default_renderers = renderers = util.Dispatcher() + + +def _render_cmd_body( + op_container: ops.OpContainer, + autogen_context: AutogenContext, +) -> str: + buf = StringIO() + printer = PythonPrinter(buf) + + printer.writeline( + "# ### commands auto generated by Alembic - please adjust! ###" + ) + + has_lines = False + for op in op_container.ops: + lines = render_op(autogen_context, op) + has_lines = has_lines or bool(lines) + + for line in lines: + printer.writeline(line) + + if not has_lines: + printer.writeline("pass") + + printer.writeline("# ### end Alembic commands ###") + + return buf.getvalue() + + +def render_op( + autogen_context: AutogenContext, op: ops.MigrateOperation +) -> List[str]: + renderer = renderers.dispatch(op) + lines = util.to_list(renderer(autogen_context, op)) + return lines + + +def render_op_text( + autogen_context: AutogenContext, op: ops.MigrateOperation +) -> str: + return "\n".join(render_op(autogen_context, op)) + + +@renderers.dispatch_for(ops.ModifyTableOps) +def _render_modify_table( + autogen_context: AutogenContext, op: ModifyTableOps +) -> List[str]: + opts = autogen_context.opts + render_as_batch = opts.get("render_as_batch", False) + + if op.ops: + lines = [] + if render_as_batch: + with autogen_context._within_batch(): + lines.append( + "with op.batch_alter_table(%r, schema=%r) as batch_op:" + % (op.table_name, op.schema) + ) + for t_op in op.ops: + t_lines = render_op(autogen_context, t_op) + lines.extend(t_lines) + lines.append("") + else: + for t_op in op.ops: + t_lines = render_op(autogen_context, t_op) + lines.extend(t_lines) + + return lines + else: + return [] + + +@renderers.dispatch_for(ops.CreateTableCommentOp) +def _render_create_table_comment( + autogen_context: AutogenContext, op: ops.CreateTableCommentOp +) -> str: + if autogen_context._has_batch: + templ = ( + "{prefix}create_table_comment(\n" + "{indent}{comment},\n" + "{indent}existing_comment={existing}\n" + ")" + ) + else: + templ = ( + "{prefix}create_table_comment(\n" + "{indent}'{tname}',\n" + "{indent}{comment},\n" + "{indent}existing_comment={existing},\n" + "{indent}schema={schema}\n" + ")" + ) + return templ.format( + prefix=_alembic_autogenerate_prefix(autogen_context), + tname=op.table_name, + comment="%r" % op.comment if op.comment is not None else None, + existing="%r" % op.existing_comment + if op.existing_comment is not None + else None, + schema="'%s'" % op.schema if op.schema is not None else None, + indent=" ", + ) + + +@renderers.dispatch_for(ops.DropTableCommentOp) +def _render_drop_table_comment( + autogen_context: AutogenContext, op: ops.DropTableCommentOp +) -> str: + if autogen_context._has_batch: + templ = ( + "{prefix}drop_table_comment(\n" + "{indent}existing_comment={existing}\n" + ")" + ) + else: + templ = ( + "{prefix}drop_table_comment(\n" + "{indent}'{tname}',\n" + "{indent}existing_comment={existing},\n" + "{indent}schema={schema}\n" + ")" + ) + return templ.format( + prefix=_alembic_autogenerate_prefix(autogen_context), + tname=op.table_name, + existing="%r" % op.existing_comment + if op.existing_comment is not None + else None, + schema="'%s'" % op.schema if op.schema is not None else None, + indent=" ", + ) + + +@renderers.dispatch_for(ops.CreateTableOp) +def _add_table(autogen_context: AutogenContext, op: ops.CreateTableOp) -> str: + table = op.to_table() + + args = [ + col + for col in [ + _render_column(col, autogen_context) for col in table.columns + ] + if col + ] + sorted( + [ + rcons + for rcons in [ + _render_constraint( + cons, autogen_context, op._namespace_metadata + ) + for cons in table.constraints + ] + if rcons is not None + ] + ) + + if len(args) > MAX_PYTHON_ARGS: + args_str = "*[" + ",\n".join(args) + "]" + else: + args_str = ",\n".join(args) + + text = "%(prefix)screate_table(%(tablename)r,\n%(args)s" % { + "tablename": _ident(op.table_name), + "prefix": _alembic_autogenerate_prefix(autogen_context), + "args": args_str, + } + if op.schema: + text += ",\nschema=%r" % _ident(op.schema) + + comment = table.comment + if comment: + text += ",\ncomment=%r" % _ident(comment) + + info = table.info + if info: + text += f",\ninfo={info!r}" + + for k in sorted(op.kw): + text += ",\n%s=%r" % (k.replace(" ", "_"), op.kw[k]) + + if table._prefixes: + prefixes = ", ".join("'%s'" % p for p in table._prefixes) + text += ",\nprefixes=[%s]" % prefixes + + text += "\n)" + return text + + +@renderers.dispatch_for(ops.DropTableOp) +def _drop_table(autogen_context: AutogenContext, op: ops.DropTableOp) -> str: + text = "%(prefix)sdrop_table(%(tname)r" % { + "prefix": _alembic_autogenerate_prefix(autogen_context), + "tname": _ident(op.table_name), + } + if op.schema: + text += ", schema=%r" % _ident(op.schema) + text += ")" + return text + + +def _render_dialect_kwargs_items( + autogen_context: AutogenContext, item: DialectKWArgs +) -> list[str]: + return [ + f"{key}={_render_potential_expr(val, autogen_context)}" + for key, val in item.dialect_kwargs.items() + ] + + +@renderers.dispatch_for(ops.CreateIndexOp) +def _add_index(autogen_context: AutogenContext, op: ops.CreateIndexOp) -> str: + index = op.to_index() + + has_batch = autogen_context._has_batch + + if has_batch: + tmpl = ( + "%(prefix)screate_index(%(name)r, [%(columns)s], " + "unique=%(unique)r%(kwargs)s)" + ) + else: + tmpl = ( + "%(prefix)screate_index(%(name)r, %(table)r, [%(columns)s], " + "unique=%(unique)r%(schema)s%(kwargs)s)" + ) + + assert index.table is not None + + opts = _render_dialect_kwargs_items(autogen_context, index) + text = tmpl % { + "prefix": _alembic_autogenerate_prefix(autogen_context), + "name": _render_gen_name(autogen_context, index.name), + "table": _ident(index.table.name), + "columns": ", ".join( + _get_index_rendered_expressions(index, autogen_context) + ), + "unique": index.unique or False, + "schema": (", schema=%r" % _ident(index.table.schema)) + if index.table.schema + else "", + "kwargs": ", " + ", ".join(opts) if opts else "", + } + return text + + +@renderers.dispatch_for(ops.DropIndexOp) +def _drop_index(autogen_context: AutogenContext, op: ops.DropIndexOp) -> str: + index = op.to_index() + + has_batch = autogen_context._has_batch + + if has_batch: + tmpl = "%(prefix)sdrop_index(%(name)r%(kwargs)s)" + else: + tmpl = ( + "%(prefix)sdrop_index(%(name)r, " + "table_name=%(table_name)r%(schema)s%(kwargs)s)" + ) + opts = _render_dialect_kwargs_items(autogen_context, index) + text = tmpl % { + "prefix": _alembic_autogenerate_prefix(autogen_context), + "name": _render_gen_name(autogen_context, op.index_name), + "table_name": _ident(op.table_name), + "schema": ((", schema=%r" % _ident(op.schema)) if op.schema else ""), + "kwargs": ", " + ", ".join(opts) if opts else "", + } + return text + + +@renderers.dispatch_for(ops.CreateUniqueConstraintOp) +def _add_unique_constraint( + autogen_context: AutogenContext, op: ops.CreateUniqueConstraintOp +) -> List[str]: + return [_uq_constraint(op.to_constraint(), autogen_context, True)] + + +@renderers.dispatch_for(ops.CreateForeignKeyOp) +def _add_fk_constraint( + autogen_context: AutogenContext, op: ops.CreateForeignKeyOp +) -> str: + args = [repr(_render_gen_name(autogen_context, op.constraint_name))] + if not autogen_context._has_batch: + args.append(repr(_ident(op.source_table))) + + args.extend( + [ + repr(_ident(op.referent_table)), + repr([_ident(col) for col in op.local_cols]), + repr([_ident(col) for col in op.remote_cols]), + ] + ) + kwargs = [ + "referent_schema", + "onupdate", + "ondelete", + "initially", + "deferrable", + "use_alter", + "match", + ] + if not autogen_context._has_batch: + kwargs.insert(0, "source_schema") + + for k in kwargs: + if k in op.kw: + value = op.kw[k] + if value is not None: + args.append("%s=%r" % (k, value)) + + return "%(prefix)screate_foreign_key(%(args)s)" % { + "prefix": _alembic_autogenerate_prefix(autogen_context), + "args": ", ".join(args), + } + + +@renderers.dispatch_for(ops.CreatePrimaryKeyOp) +def _add_pk_constraint(constraint, autogen_context): + raise NotImplementedError() + + +@renderers.dispatch_for(ops.CreateCheckConstraintOp) +def _add_check_constraint(constraint, autogen_context): + raise NotImplementedError() + + +@renderers.dispatch_for(ops.DropConstraintOp) +def _drop_constraint( + autogen_context: AutogenContext, op: ops.DropConstraintOp +) -> str: + prefix = _alembic_autogenerate_prefix(autogen_context) + name = _render_gen_name(autogen_context, op.constraint_name) + schema = _ident(op.schema) if op.schema else None + type_ = _ident(op.constraint_type) if op.constraint_type else None + + params_strs = [] + params_strs.append(repr(name)) + if not autogen_context._has_batch: + params_strs.append(repr(_ident(op.table_name))) + if schema is not None: + params_strs.append(f"schema={schema!r}") + if type_ is not None: + params_strs.append(f"type_={type_!r}") + + return f"{prefix}drop_constraint({', '.join(params_strs)})" + + +@renderers.dispatch_for(ops.AddColumnOp) +def _add_column(autogen_context: AutogenContext, op: ops.AddColumnOp) -> str: + schema, tname, column = op.schema, op.table_name, op.column + if autogen_context._has_batch: + template = "%(prefix)sadd_column(%(column)s)" + else: + template = "%(prefix)sadd_column(%(tname)r, %(column)s" + if schema: + template += ", schema=%(schema)r" + template += ")" + text = template % { + "prefix": _alembic_autogenerate_prefix(autogen_context), + "tname": tname, + "column": _render_column(column, autogen_context), + "schema": schema, + } + return text + + +@renderers.dispatch_for(ops.DropColumnOp) +def _drop_column(autogen_context: AutogenContext, op: ops.DropColumnOp) -> str: + schema, tname, column_name = op.schema, op.table_name, op.column_name + + if autogen_context._has_batch: + template = "%(prefix)sdrop_column(%(cname)r)" + else: + template = "%(prefix)sdrop_column(%(tname)r, %(cname)r" + if schema: + template += ", schema=%(schema)r" + template += ")" + + text = template % { + "prefix": _alembic_autogenerate_prefix(autogen_context), + "tname": _ident(tname), + "cname": _ident(column_name), + "schema": _ident(schema), + } + return text + + +@renderers.dispatch_for(ops.AlterColumnOp) +def _alter_column( + autogen_context: AutogenContext, op: ops.AlterColumnOp +) -> str: + tname = op.table_name + cname = op.column_name + server_default = op.modify_server_default + type_ = op.modify_type + nullable = op.modify_nullable + comment = op.modify_comment + autoincrement = op.kw.get("autoincrement", None) + existing_type = op.existing_type + existing_nullable = op.existing_nullable + existing_comment = op.existing_comment + existing_server_default = op.existing_server_default + schema = op.schema + + indent = " " * 11 + + if autogen_context._has_batch: + template = "%(prefix)salter_column(%(cname)r" + else: + template = "%(prefix)salter_column(%(tname)r, %(cname)r" + + text = template % { + "prefix": _alembic_autogenerate_prefix(autogen_context), + "tname": tname, + "cname": cname, + } + if existing_type is not None: + text += ",\n%sexisting_type=%s" % ( + indent, + _repr_type(existing_type, autogen_context), + ) + if server_default is not False: + rendered = _render_server_default(server_default, autogen_context) + text += ",\n%sserver_default=%s" % (indent, rendered) + + if type_ is not None: + text += ",\n%stype_=%s" % (indent, _repr_type(type_, autogen_context)) + if nullable is not None: + text += ",\n%snullable=%r" % (indent, nullable) + if comment is not False: + text += ",\n%scomment=%r" % (indent, comment) + if existing_comment is not None: + text += ",\n%sexisting_comment=%r" % (indent, existing_comment) + if nullable is None and existing_nullable is not None: + text += ",\n%sexisting_nullable=%r" % (indent, existing_nullable) + if autoincrement is not None: + text += ",\n%sautoincrement=%r" % (indent, autoincrement) + if server_default is False and existing_server_default: + rendered = _render_server_default( + existing_server_default, autogen_context + ) + text += ",\n%sexisting_server_default=%s" % (indent, rendered) + if schema and not autogen_context._has_batch: + text += ",\n%sschema=%r" % (indent, schema) + text += ")" + return text + + +class _f_name: + def __init__(self, prefix: str, name: conv) -> None: + self.prefix = prefix + self.name = name + + def __repr__(self) -> str: + return "%sf(%r)" % (self.prefix, _ident(self.name)) + + +def _ident(name: Optional[Union[quoted_name, str]]) -> Optional[str]: + """produce a __repr__() object for a string identifier that may + use quoted_name() in SQLAlchemy 0.9 and greater. + + The issue worked around here is that quoted_name() doesn't have + very good repr() behavior by itself when unicode is involved. + + """ + if name is None: + return name + elif isinstance(name, quoted_name): + return str(name) + elif isinstance(name, str): + return name + + +def _render_potential_expr( + value: Any, + autogen_context: AutogenContext, + *, + wrap_in_text: bool = True, + is_server_default: bool = False, + is_index: bool = False, +) -> str: + if isinstance(value, sql.ClauseElement): + if wrap_in_text: + template = "%(prefix)stext(%(sql)r)" + else: + template = "%(sql)r" + + return template % { + "prefix": _sqlalchemy_autogenerate_prefix(autogen_context), + "sql": autogen_context.migration_context.impl.render_ddl_sql_expr( + value, is_server_default=is_server_default, is_index=is_index + ), + } + + else: + return repr(value) + + +def _get_index_rendered_expressions( + idx: Index, autogen_context: AutogenContext +) -> List[str]: + return [ + repr(_ident(getattr(exp, "name", None))) + if isinstance(exp, sa_schema.Column) + else _render_potential_expr(exp, autogen_context, is_index=True) + for exp in idx.expressions + ] + + +def _uq_constraint( + constraint: UniqueConstraint, + autogen_context: AutogenContext, + alter: bool, +) -> str: + opts: List[Tuple[str, Any]] = [] + + has_batch = autogen_context._has_batch + + if constraint.deferrable: + opts.append(("deferrable", str(constraint.deferrable))) + if constraint.initially: + opts.append(("initially", str(constraint.initially))) + if not has_batch and alter and constraint.table.schema: + opts.append(("schema", _ident(constraint.table.schema))) + if not alter and constraint.name: + opts.append( + ("name", _render_gen_name(autogen_context, constraint.name)) + ) + dialect_options = _render_dialect_kwargs_items(autogen_context, constraint) + + if alter: + args = [repr(_render_gen_name(autogen_context, constraint.name))] + if not has_batch: + args += [repr(_ident(constraint.table.name))] + args.append(repr([_ident(col.name) for col in constraint.columns])) + args.extend(["%s=%r" % (k, v) for k, v in opts]) + args.extend(dialect_options) + return "%(prefix)screate_unique_constraint(%(args)s)" % { + "prefix": _alembic_autogenerate_prefix(autogen_context), + "args": ", ".join(args), + } + else: + args = [repr(_ident(col.name)) for col in constraint.columns] + args.extend(["%s=%r" % (k, v) for k, v in opts]) + args.extend(dialect_options) + return "%(prefix)sUniqueConstraint(%(args)s)" % { + "prefix": _sqlalchemy_autogenerate_prefix(autogen_context), + "args": ", ".join(args), + } + + +def _user_autogenerate_prefix(autogen_context, target): + prefix = autogen_context.opts["user_module_prefix"] + if prefix is None: + return "%s." % target.__module__ + else: + return prefix + + +def _sqlalchemy_autogenerate_prefix(autogen_context: AutogenContext) -> str: + return autogen_context.opts["sqlalchemy_module_prefix"] or "" + + +def _alembic_autogenerate_prefix(autogen_context: AutogenContext) -> str: + if autogen_context._has_batch: + return "batch_op." + else: + return autogen_context.opts["alembic_module_prefix"] or "" + + +def _user_defined_render( + type_: str, object_: Any, autogen_context: AutogenContext +) -> Union[str, Literal[False]]: + if "render_item" in autogen_context.opts: + render = autogen_context.opts["render_item"] + if render: + rendered = render(type_, object_, autogen_context) + if rendered is not False: + return rendered + return False + + +def _render_column( + column: Column[Any], autogen_context: AutogenContext +) -> str: + rendered = _user_defined_render("column", column, autogen_context) + if rendered is not False: + return rendered + + args: List[str] = [] + opts: List[Tuple[str, Any]] = [] + + if column.server_default: + rendered = _render_server_default( # type:ignore[assignment] + column.server_default, autogen_context + ) + if rendered: + if _should_render_server_default_positionally( + column.server_default + ): + args.append(rendered) + else: + opts.append(("server_default", rendered)) + + if ( + column.autoincrement is not None + and column.autoincrement != sqla_compat.AUTOINCREMENT_DEFAULT + ): + opts.append(("autoincrement", column.autoincrement)) + + if column.nullable is not None: + opts.append(("nullable", column.nullable)) + + if column.system: + opts.append(("system", column.system)) + + comment = column.comment + if comment: + opts.append(("comment", "%r" % comment)) + + # TODO: for non-ascii colname, assign a "key" + return "%(prefix)sColumn(%(name)r, %(type)s, %(args)s%(kwargs)s)" % { + "prefix": _sqlalchemy_autogenerate_prefix(autogen_context), + "name": _ident(column.name), + "type": _repr_type(column.type, autogen_context), + "args": ", ".join([str(arg) for arg in args]) + ", " if args else "", + "kwargs": ( + ", ".join( + ["%s=%s" % (kwname, val) for kwname, val in opts] + + [ + "%s=%s" + % (key, _render_potential_expr(val, autogen_context)) + for key, val in sqla_compat._column_kwargs(column).items() + ] + ) + ), + } + + +def _should_render_server_default_positionally(server_default: Any) -> bool: + return sqla_compat._server_default_is_computed( + server_default + ) or sqla_compat._server_default_is_identity(server_default) + + +def _render_server_default( + default: Optional[ + Union[FetchedValue, str, TextClause, ColumnElement[Any]] + ], + autogen_context: AutogenContext, + repr_: bool = True, +) -> Optional[str]: + rendered = _user_defined_render("server_default", default, autogen_context) + if rendered is not False: + return rendered + + if sqla_compat._server_default_is_computed(default): + return _render_computed(cast("Computed", default), autogen_context) + elif sqla_compat._server_default_is_identity(default): + return _render_identity(cast("Identity", default), autogen_context) + elif isinstance(default, sa_schema.DefaultClause): + if isinstance(default.arg, str): + default = default.arg + else: + return _render_potential_expr( + default.arg, autogen_context, is_server_default=True + ) + + if isinstance(default, str) and repr_: + default = repr(re.sub(r"^'|'$", "", default)) + + return cast(str, default) + + +def _render_computed( + computed: Computed, autogen_context: AutogenContext +) -> str: + text = _render_potential_expr( + computed.sqltext, autogen_context, wrap_in_text=False + ) + + kwargs = {} + if computed.persisted is not None: + kwargs["persisted"] = computed.persisted + return "%(prefix)sComputed(%(text)s, %(kwargs)s)" % { + "prefix": _sqlalchemy_autogenerate_prefix(autogen_context), + "text": text, + "kwargs": (", ".join("%s=%s" % pair for pair in kwargs.items())), + } + + +def _render_identity( + identity: Identity, autogen_context: AutogenContext +) -> str: + kwargs = sqla_compat._get_identity_options_dict( + identity, dialect_kwargs=True + ) + + return "%(prefix)sIdentity(%(kwargs)s)" % { + "prefix": _sqlalchemy_autogenerate_prefix(autogen_context), + "kwargs": (", ".join("%s=%s" % pair for pair in kwargs.items())), + } + + +def _repr_type( + type_: TypeEngine, + autogen_context: AutogenContext, + _skip_variants: bool = False, +) -> str: + rendered = _user_defined_render("type", type_, autogen_context) + if rendered is not False: + return rendered + + if hasattr(autogen_context.migration_context, "impl"): + impl_rt = autogen_context.migration_context.impl.render_type( + type_, autogen_context + ) + else: + impl_rt = None + + mod = type(type_).__module__ + imports = autogen_context.imports + if mod.startswith("sqlalchemy.dialects"): + match = re.match(r"sqlalchemy\.dialects\.(\w+)", mod) + assert match is not None + dname = match.group(1) + if imports is not None: + imports.add("from sqlalchemy.dialects import %s" % dname) + if impl_rt: + return impl_rt + else: + return "%s.%r" % (dname, type_) + elif impl_rt: + return impl_rt + elif not _skip_variants and sqla_compat._type_has_variants(type_): + return _render_Variant_type(type_, autogen_context) + elif mod.startswith("sqlalchemy."): + if "_render_%s_type" % type_.__visit_name__ in globals(): + fn = globals()["_render_%s_type" % type_.__visit_name__] + return fn(type_, autogen_context) + else: + prefix = _sqlalchemy_autogenerate_prefix(autogen_context) + return "%s%r" % (prefix, type_) + else: + prefix = _user_autogenerate_prefix(autogen_context, type_) + return "%s%r" % (prefix, type_) + + +def _render_ARRAY_type(type_: ARRAY, autogen_context: AutogenContext) -> str: + return cast( + str, + _render_type_w_subtype( + type_, autogen_context, "item_type", r"(.+?\()" + ), + ) + + +def _render_Variant_type( + type_: TypeEngine, autogen_context: AutogenContext +) -> str: + base_type, variant_mapping = sqla_compat._get_variant_mapping(type_) + base = _repr_type(base_type, autogen_context, _skip_variants=True) + assert base is not None and base is not False # type: ignore[comparison-overlap] # noqa:E501 + for dialect in sorted(variant_mapping): + typ = variant_mapping[dialect] + base += ".with_variant(%s, %r)" % ( + _repr_type(typ, autogen_context, _skip_variants=True), + dialect, + ) + return base + + +def _render_type_w_subtype( + type_: TypeEngine, + autogen_context: AutogenContext, + attrname: str, + regexp: str, + prefix: Optional[str] = None, +) -> Union[Optional[str], Literal[False]]: + outer_repr = repr(type_) + inner_type = getattr(type_, attrname, None) + if inner_type is None: + return False + + inner_repr = repr(inner_type) + + inner_repr = re.sub(r"([\(\)])", r"\\\1", inner_repr) + sub_type = _repr_type(getattr(type_, attrname), autogen_context) + outer_type = re.sub(regexp + inner_repr, r"\1%s" % sub_type, outer_repr) + + if prefix: + return "%s%s" % (prefix, outer_type) + + mod = type(type_).__module__ + if mod.startswith("sqlalchemy.dialects"): + match = re.match(r"sqlalchemy\.dialects\.(\w+)", mod) + assert match is not None + dname = match.group(1) + return "%s.%s" % (dname, outer_type) + elif mod.startswith("sqlalchemy"): + prefix = _sqlalchemy_autogenerate_prefix(autogen_context) + return "%s%s" % (prefix, outer_type) + else: + return None + + +_constraint_renderers = util.Dispatcher() + + +def _render_constraint( + constraint: Constraint, + autogen_context: AutogenContext, + namespace_metadata: Optional[MetaData], +) -> Optional[str]: + try: + renderer = _constraint_renderers.dispatch(constraint) + except ValueError: + util.warn("No renderer is established for object %r" % constraint) + return "[Unknown Python object %r]" % constraint + else: + return renderer(constraint, autogen_context, namespace_metadata) + + +@_constraint_renderers.dispatch_for(sa_schema.PrimaryKeyConstraint) +def _render_primary_key( + constraint: PrimaryKeyConstraint, + autogen_context: AutogenContext, + namespace_metadata: Optional[MetaData], +) -> Optional[str]: + rendered = _user_defined_render("primary_key", constraint, autogen_context) + if rendered is not False: + return rendered + + if not constraint.columns: + return None + + opts = [] + if constraint.name: + opts.append( + ("name", repr(_render_gen_name(autogen_context, constraint.name))) + ) + return "%(prefix)sPrimaryKeyConstraint(%(args)s)" % { + "prefix": _sqlalchemy_autogenerate_prefix(autogen_context), + "args": ", ".join( + [repr(c.name) for c in constraint.columns] + + ["%s=%s" % (kwname, val) for kwname, val in opts] + ), + } + + +def _fk_colspec( + fk: ForeignKey, + metadata_schema: Optional[str], + namespace_metadata: MetaData, +) -> str: + """Implement a 'safe' version of ForeignKey._get_colspec() that + won't fail if the remote table can't be resolved. + + """ + colspec = fk._get_colspec() + tokens = colspec.split(".") + tname, colname = tokens[-2:] + + if metadata_schema is not None and len(tokens) == 2: + table_fullname = "%s.%s" % (metadata_schema, tname) + else: + table_fullname = ".".join(tokens[0:-1]) + + if ( + not fk.link_to_name + and fk.parent is not None + and fk.parent.table is not None + ): + # try to resolve the remote table in order to adjust for column.key. + # the FK constraint needs to be rendered in terms of the column + # name. + + if table_fullname in namespace_metadata.tables: + col = namespace_metadata.tables[table_fullname].c.get(colname) + if col is not None: + colname = _ident(col.name) # type: ignore[assignment] + + colspec = "%s.%s" % (table_fullname, colname) + + return colspec + + +def _populate_render_fk_opts( + constraint: ForeignKeyConstraint, opts: List[Tuple[str, str]] +) -> None: + if constraint.onupdate: + opts.append(("onupdate", repr(constraint.onupdate))) + if constraint.ondelete: + opts.append(("ondelete", repr(constraint.ondelete))) + if constraint.initially: + opts.append(("initially", repr(constraint.initially))) + if constraint.deferrable: + opts.append(("deferrable", repr(constraint.deferrable))) + if constraint.use_alter: + opts.append(("use_alter", repr(constraint.use_alter))) + if constraint.match: + opts.append(("match", repr(constraint.match))) + + +@_constraint_renderers.dispatch_for(sa_schema.ForeignKeyConstraint) +def _render_foreign_key( + constraint: ForeignKeyConstraint, + autogen_context: AutogenContext, + namespace_metadata: MetaData, +) -> Optional[str]: + rendered = _user_defined_render("foreign_key", constraint, autogen_context) + if rendered is not False: + return rendered + + opts = [] + if constraint.name: + opts.append( + ("name", repr(_render_gen_name(autogen_context, constraint.name))) + ) + + _populate_render_fk_opts(constraint, opts) + + apply_metadata_schema = namespace_metadata.schema + return ( + "%(prefix)sForeignKeyConstraint([%(cols)s], " + "[%(refcols)s], %(args)s)" + % { + "prefix": _sqlalchemy_autogenerate_prefix(autogen_context), + "cols": ", ".join( + repr(_ident(f.parent.name)) for f in constraint.elements + ), + "refcols": ", ".join( + repr(_fk_colspec(f, apply_metadata_schema, namespace_metadata)) + for f in constraint.elements + ), + "args": ", ".join( + ["%s=%s" % (kwname, val) for kwname, val in opts] + ), + } + ) + + +@_constraint_renderers.dispatch_for(sa_schema.UniqueConstraint) +def _render_unique_constraint( + constraint: UniqueConstraint, + autogen_context: AutogenContext, + namespace_metadata: Optional[MetaData], +) -> str: + rendered = _user_defined_render("unique", constraint, autogen_context) + if rendered is not False: + return rendered + + return _uq_constraint(constraint, autogen_context, False) + + +@_constraint_renderers.dispatch_for(sa_schema.CheckConstraint) +def _render_check_constraint( + constraint: CheckConstraint, + autogen_context: AutogenContext, + namespace_metadata: Optional[MetaData], +) -> Optional[str]: + rendered = _user_defined_render("check", constraint, autogen_context) + if rendered is not False: + return rendered + + # detect the constraint being part of + # a parent type which is probably in the Table already. + # ideally SQLAlchemy would give us more of a first class + # way to detect this. + if ( + constraint._create_rule + and hasattr(constraint._create_rule, "target") + and isinstance( + constraint._create_rule.target, + sqltypes.TypeEngine, + ) + ): + return None + opts = [] + if constraint.name: + opts.append( + ("name", repr(_render_gen_name(autogen_context, constraint.name))) + ) + return "%(prefix)sCheckConstraint(%(sqltext)s%(opts)s)" % { + "prefix": _sqlalchemy_autogenerate_prefix(autogen_context), + "opts": ", " + (", ".join("%s=%s" % (k, v) for k, v in opts)) + if opts + else "", + "sqltext": _render_potential_expr( + constraint.sqltext, autogen_context, wrap_in_text=False + ), + } + + +@renderers.dispatch_for(ops.ExecuteSQLOp) +def _execute_sql(autogen_context: AutogenContext, op: ops.ExecuteSQLOp) -> str: + if not isinstance(op.sqltext, str): + raise NotImplementedError( + "Autogenerate rendering of SQL Expression language constructs " + "not supported here; please use a plain SQL string" + ) + return "op.execute(%r)" % op.sqltext + + +renderers = default_renderers.branch() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/rewriter.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/rewriter.py new file mode 100644 index 0000000000000000000000000000000000000000..8994dcf823cb3e40ddbab287cd7b80b166ae885b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/autogenerate/rewriter.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +from typing import Any +from typing import Callable +from typing import Iterator +from typing import List +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import Union + +from .. import util +from ..operations import ops + +if TYPE_CHECKING: + from ..operations.ops import AddColumnOp + from ..operations.ops import AlterColumnOp + from ..operations.ops import CreateTableOp + from ..operations.ops import DowngradeOps + from ..operations.ops import MigrateOperation + from ..operations.ops import MigrationScript + from ..operations.ops import ModifyTableOps + from ..operations.ops import OpContainer + from ..operations.ops import UpgradeOps + from ..runtime.migration import MigrationContext + from ..script.revision import _GetRevArg + +ProcessRevisionDirectiveFn = Callable[ + ["MigrationContext", "_GetRevArg", List["MigrationScript"]], None +] + + +class Rewriter: + """A helper object that allows easy 'rewriting' of ops streams. + + The :class:`.Rewriter` object is intended to be passed along + to the + :paramref:`.EnvironmentContext.configure.process_revision_directives` + parameter in an ``env.py`` script. Once constructed, any number + of "rewrites" functions can be associated with it, which will be given + the opportunity to modify the structure without having to have explicit + knowledge of the overall structure. + + The function is passed the :class:`.MigrationContext` object and + ``revision`` tuple that are passed to the :paramref:`.Environment + Context.configure.process_revision_directives` function normally, + and the third argument is an individual directive of the type + noted in the decorator. The function has the choice of returning + a single op directive, which normally can be the directive that + was actually passed, or a new directive to replace it, or a list + of zero or more directives to replace it. + + .. seealso:: + + :ref:`autogen_rewriter` - usage example + + """ + + _traverse = util.Dispatcher() + + _chained: Tuple[Union[ProcessRevisionDirectiveFn, Rewriter], ...] = () + + def __init__(self) -> None: + self.dispatch = util.Dispatcher() + + def chain( + self, + other: Union[ + ProcessRevisionDirectiveFn, + Rewriter, + ], + ) -> Rewriter: + """Produce a "chain" of this :class:`.Rewriter` to another. + + This allows two or more rewriters to operate serially on a stream, + e.g.:: + + writer1 = autogenerate.Rewriter() + writer2 = autogenerate.Rewriter() + + + @writer1.rewrites(ops.AddColumnOp) + def add_column_nullable(context, revision, op): + op.column.nullable = True + return op + + + @writer2.rewrites(ops.AddColumnOp) + def add_column_idx(context, revision, op): + idx_op = ops.CreateIndexOp( + "ixc", op.table_name, [op.column.name] + ) + return [op, idx_op] + + writer = writer1.chain(writer2) + + :param other: a :class:`.Rewriter` instance + :return: a new :class:`.Rewriter` that will run the operations + of this writer, then the "other" writer, in succession. + + """ + wr = self.__class__.__new__(self.__class__) + wr.__dict__.update(self.__dict__) + wr._chained += (other,) + return wr + + def rewrites( + self, + operator: Union[ + Type[AddColumnOp], + Type[MigrateOperation], + Type[AlterColumnOp], + Type[CreateTableOp], + Type[ModifyTableOps], + ], + ) -> Callable[..., Any]: + """Register a function as rewriter for a given type. + + The function should receive three arguments, which are + the :class:`.MigrationContext`, a ``revision`` tuple, and + an op directive of the type indicated. E.g.:: + + @writer1.rewrites(ops.AddColumnOp) + def add_column_nullable(context, revision, op): + op.column.nullable = True + return op + + """ + return self.dispatch.dispatch_for(operator) + + def _rewrite( + self, + context: MigrationContext, + revision: _GetRevArg, + directive: MigrateOperation, + ) -> Iterator[MigrateOperation]: + try: + _rewriter = self.dispatch.dispatch(directive) + except ValueError: + _rewriter = None + yield directive + else: + if self in directive._mutations: + yield directive + else: + for r_directive in util.to_list( + _rewriter(context, revision, directive), [] + ): + r_directive._mutations = r_directive._mutations.union( + [self] + ) + yield r_directive + + def __call__( + self, + context: MigrationContext, + revision: _GetRevArg, + directives: List[MigrationScript], + ) -> None: + self.process_revision_directives(context, revision, directives) + for process_revision_directives in self._chained: + process_revision_directives(context, revision, directives) + + @_traverse.dispatch_for(ops.MigrationScript) + def _traverse_script( + self, + context: MigrationContext, + revision: _GetRevArg, + directive: MigrationScript, + ) -> None: + upgrade_ops_list: List[UpgradeOps] = [] + for upgrade_ops in directive.upgrade_ops_list: + ret = self._traverse_for(context, revision, upgrade_ops) + if len(ret) != 1: + raise ValueError( + "Can only return single object for UpgradeOps traverse" + ) + upgrade_ops_list.append(ret[0]) + + directive.upgrade_ops = upgrade_ops_list # type: ignore + + downgrade_ops_list: List[DowngradeOps] = [] + for downgrade_ops in directive.downgrade_ops_list: + ret = self._traverse_for(context, revision, downgrade_ops) + if len(ret) != 1: + raise ValueError( + "Can only return single object for DowngradeOps traverse" + ) + downgrade_ops_list.append(ret[0]) + directive.downgrade_ops = downgrade_ops_list # type: ignore + + @_traverse.dispatch_for(ops.OpContainer) + def _traverse_op_container( + self, + context: MigrationContext, + revision: _GetRevArg, + directive: OpContainer, + ) -> None: + self._traverse_list(context, revision, directive.ops) + + @_traverse.dispatch_for(ops.MigrateOperation) + def _traverse_any_directive( + self, + context: MigrationContext, + revision: _GetRevArg, + directive: MigrateOperation, + ) -> None: + pass + + def _traverse_for( + self, + context: MigrationContext, + revision: _GetRevArg, + directive: MigrateOperation, + ) -> Any: + directives = list(self._rewrite(context, revision, directive)) + for directive in directives: + traverser = self._traverse.dispatch(directive) + traverser(self, context, revision, directive) + return directives + + def _traverse_list( + self, + context: MigrationContext, + revision: _GetRevArg, + directives: Any, + ) -> None: + dest = [] + for directive in directives: + dest.extend(self._traverse_for(context, revision, directive)) + + directives[:] = dest + + def process_revision_directives( + self, + context: MigrationContext, + revision: _GetRevArg, + directives: List[MigrationScript], + ) -> None: + self._traverse_list(context, revision, directives) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f72b3dd8d3748b36cb7acfcda7abf8468b6926 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/__init__.py @@ -0,0 +1,6 @@ +from . import mssql +from . import mysql +from . import oracle +from . import postgresql +from . import sqlite +from .impl import DefaultImpl as DefaultImpl diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/_autogen.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/_autogen.py new file mode 100644 index 0000000000000000000000000000000000000000..e22153c49c761451c074c11de6c7ea53d20c1149 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/_autogen.py @@ -0,0 +1,325 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +from typing import Any +from typing import ClassVar +from typing import Dict +from typing import Generic +from typing import NamedTuple +from typing import Optional +from typing import Sequence +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from sqlalchemy.sql.schema import Constraint +from sqlalchemy.sql.schema import ForeignKeyConstraint +from sqlalchemy.sql.schema import Index +from sqlalchemy.sql.schema import UniqueConstraint +from typing_extensions import TypeGuard + +from .. import util +from ..util import sqla_compat + +if TYPE_CHECKING: + from typing import Literal + + from alembic.autogenerate.api import AutogenContext + from alembic.ddl.impl import DefaultImpl + +CompareConstraintType = Union[Constraint, Index] + +_C = TypeVar("_C", bound=CompareConstraintType) + +_clsreg: Dict[str, Type[_constraint_sig]] = {} + + +class ComparisonResult(NamedTuple): + status: Literal["equal", "different", "skip"] + message: str + + @property + def is_equal(self) -> bool: + return self.status == "equal" + + @property + def is_different(self) -> bool: + return self.status == "different" + + @property + def is_skip(self) -> bool: + return self.status == "skip" + + @classmethod + def Equal(cls) -> ComparisonResult: + """the constraints are equal.""" + return cls("equal", "The two constraints are equal") + + @classmethod + def Different(cls, reason: Union[str, Sequence[str]]) -> ComparisonResult: + """the constraints are different for the provided reason(s).""" + return cls("different", ", ".join(util.to_list(reason))) + + @classmethod + def Skip(cls, reason: Union[str, Sequence[str]]) -> ComparisonResult: + """the constraint cannot be compared for the provided reason(s). + + The message is logged, but the constraints will be otherwise + considered equal, meaning that no migration command will be + generated. + """ + return cls("skip", ", ".join(util.to_list(reason))) + + +class _constraint_sig(Generic[_C]): + const: _C + + _sig: Tuple[Any, ...] + name: Optional[sqla_compat._ConstraintNameDefined] + + impl: DefaultImpl + + _is_index: ClassVar[bool] = False + _is_fk: ClassVar[bool] = False + _is_uq: ClassVar[bool] = False + + _is_metadata: bool + + def __init_subclass__(cls) -> None: + cls._register() + + @classmethod + def _register(cls): + raise NotImplementedError() + + def __init__( + self, is_metadata: bool, impl: DefaultImpl, const: _C + ) -> None: + raise NotImplementedError() + + def compare_to_reflected( + self, other: _constraint_sig[Any] + ) -> ComparisonResult: + assert self.impl is other.impl + assert self._is_metadata + assert not other._is_metadata + + return self._compare_to_reflected(other) + + def _compare_to_reflected( + self, other: _constraint_sig[_C] + ) -> ComparisonResult: + raise NotImplementedError() + + @classmethod + def from_constraint( + cls, is_metadata: bool, impl: DefaultImpl, constraint: _C + ) -> _constraint_sig[_C]: + # these could be cached by constraint/impl, however, if the + # constraint is modified in place, then the sig is wrong. the mysql + # impl currently does this, and if we fixed that we can't be sure + # someone else might do it too, so play it safe. + sig = _clsreg[constraint.__visit_name__](is_metadata, impl, constraint) + return sig + + def md_name_to_sql_name(self, context: AutogenContext) -> Optional[str]: + return sqla_compat._get_constraint_final_name( + self.const, context.dialect + ) + + @util.memoized_property + def is_named(self): + return sqla_compat._constraint_is_named(self.const, self.impl.dialect) + + @util.memoized_property + def unnamed(self) -> Tuple[Any, ...]: + return self._sig + + @util.memoized_property + def unnamed_no_options(self) -> Tuple[Any, ...]: + raise NotImplementedError() + + @util.memoized_property + def _full_sig(self) -> Tuple[Any, ...]: + return (self.name,) + self.unnamed + + def __eq__(self, other) -> bool: + return self._full_sig == other._full_sig + + def __ne__(self, other) -> bool: + return self._full_sig != other._full_sig + + def __hash__(self) -> int: + return hash(self._full_sig) + + +class _uq_constraint_sig(_constraint_sig[UniqueConstraint]): + _is_uq = True + + @classmethod + def _register(cls) -> None: + _clsreg["unique_constraint"] = cls + + is_unique = True + + def __init__( + self, + is_metadata: bool, + impl: DefaultImpl, + const: UniqueConstraint, + ) -> None: + self.impl = impl + self.const = const + self.name = sqla_compat.constraint_name_or_none(const.name) + self._sig = tuple(sorted([col.name for col in const.columns])) + self._is_metadata = is_metadata + + @property + def column_names(self) -> Tuple[str, ...]: + return tuple([col.name for col in self.const.columns]) + + def _compare_to_reflected( + self, other: _constraint_sig[_C] + ) -> ComparisonResult: + assert self._is_metadata + metadata_obj = self + conn_obj = other + + assert is_uq_sig(conn_obj) + return self.impl.compare_unique_constraint( + metadata_obj.const, conn_obj.const + ) + + +class _ix_constraint_sig(_constraint_sig[Index]): + _is_index = True + + name: sqla_compat._ConstraintName + + @classmethod + def _register(cls) -> None: + _clsreg["index"] = cls + + def __init__( + self, is_metadata: bool, impl: DefaultImpl, const: Index + ) -> None: + self.impl = impl + self.const = const + self.name = const.name + self.is_unique = bool(const.unique) + self._is_metadata = is_metadata + + def _compare_to_reflected( + self, other: _constraint_sig[_C] + ) -> ComparisonResult: + assert self._is_metadata + metadata_obj = self + conn_obj = other + + assert is_index_sig(conn_obj) + return self.impl.compare_indexes(metadata_obj.const, conn_obj.const) + + @util.memoized_property + def has_expressions(self): + return sqla_compat.is_expression_index(self.const) + + @util.memoized_property + def column_names(self) -> Tuple[str, ...]: + return tuple([col.name for col in self.const.columns]) + + @util.memoized_property + def column_names_optional(self) -> Tuple[Optional[str], ...]: + return tuple( + [getattr(col, "name", None) for col in self.const.expressions] + ) + + @util.memoized_property + def is_named(self): + return True + + @util.memoized_property + def unnamed(self): + return (self.is_unique,) + self.column_names_optional + + +class _fk_constraint_sig(_constraint_sig[ForeignKeyConstraint]): + _is_fk = True + + @classmethod + def _register(cls) -> None: + _clsreg["foreign_key_constraint"] = cls + + def __init__( + self, + is_metadata: bool, + impl: DefaultImpl, + const: ForeignKeyConstraint, + ) -> None: + self._is_metadata = is_metadata + + self.impl = impl + self.const = const + + self.name = sqla_compat.constraint_name_or_none(const.name) + + ( + self.source_schema, + self.source_table, + self.source_columns, + self.target_schema, + self.target_table, + self.target_columns, + onupdate, + ondelete, + deferrable, + initially, + ) = sqla_compat._fk_spec(const) + + self._sig: Tuple[Any, ...] = ( + self.source_schema, + self.source_table, + tuple(self.source_columns), + self.target_schema, + self.target_table, + tuple(self.target_columns), + ) + ( + (None if onupdate.lower() == "no action" else onupdate.lower()) + if onupdate + else None, + (None if ondelete.lower() == "no action" else ondelete.lower()) + if ondelete + else None, + # convert initially + deferrable into one three-state value + "initially_deferrable" + if initially and initially.lower() == "deferred" + else "deferrable" + if deferrable + else "not deferrable", + ) + + @util.memoized_property + def unnamed_no_options(self): + return ( + self.source_schema, + self.source_table, + tuple(self.source_columns), + self.target_schema, + self.target_table, + tuple(self.target_columns), + ) + + +def is_index_sig(sig: _constraint_sig) -> TypeGuard[_ix_constraint_sig]: + return sig._is_index + + +def is_uq_sig(sig: _constraint_sig) -> TypeGuard[_uq_constraint_sig]: + return sig._is_uq + + +def is_fk_sig(sig: _constraint_sig) -> TypeGuard[_fk_constraint_sig]: + return sig._is_fk diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/base.py new file mode 100644 index 0000000000000000000000000000000000000000..7a85a5c198affa8f50fcfe4da126836627ae472c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/base.py @@ -0,0 +1,335 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +import functools +from typing import Optional +from typing import TYPE_CHECKING +from typing import Union + +from sqlalchemy import exc +from sqlalchemy import Integer +from sqlalchemy import types as sqltypes +from sqlalchemy.ext.compiler import compiles +from sqlalchemy.schema import Column +from sqlalchemy.schema import DDLElement +from sqlalchemy.sql.elements import quoted_name + +from ..util.sqla_compat import _columns_for_constraint # noqa +from ..util.sqla_compat import _find_columns # noqa +from ..util.sqla_compat import _fk_spec # noqa +from ..util.sqla_compat import _is_type_bound # noqa +from ..util.sqla_compat import _table_for_constraint # noqa + +if TYPE_CHECKING: + from typing import Any + + from sqlalchemy.sql.compiler import Compiled + from sqlalchemy.sql.compiler import DDLCompiler + from sqlalchemy.sql.elements import TextClause + from sqlalchemy.sql.functions import Function + from sqlalchemy.sql.schema import FetchedValue + from sqlalchemy.sql.type_api import TypeEngine + + from .impl import DefaultImpl + from ..util.sqla_compat import Computed + from ..util.sqla_compat import Identity + +_ServerDefault = Union["TextClause", "FetchedValue", "Function[Any]", str] + + +class AlterTable(DDLElement): + + """Represent an ALTER TABLE statement. + + Only the string name and optional schema name of the table + is required, not a full Table object. + + """ + + def __init__( + self, + table_name: str, + schema: Optional[Union[quoted_name, str]] = None, + ) -> None: + self.table_name = table_name + self.schema = schema + + +class RenameTable(AlterTable): + def __init__( + self, + old_table_name: str, + new_table_name: Union[quoted_name, str], + schema: Optional[Union[quoted_name, str]] = None, + ) -> None: + super().__init__(old_table_name, schema=schema) + self.new_table_name = new_table_name + + +class AlterColumn(AlterTable): + def __init__( + self, + name: str, + column_name: str, + schema: Optional[str] = None, + existing_type: Optional[TypeEngine] = None, + existing_nullable: Optional[bool] = None, + existing_server_default: Optional[_ServerDefault] = None, + existing_comment: Optional[str] = None, + ) -> None: + super().__init__(name, schema=schema) + self.column_name = column_name + self.existing_type = ( + sqltypes.to_instance(existing_type) + if existing_type is not None + else None + ) + self.existing_nullable = existing_nullable + self.existing_server_default = existing_server_default + self.existing_comment = existing_comment + + +class ColumnNullable(AlterColumn): + def __init__( + self, name: str, column_name: str, nullable: bool, **kw + ) -> None: + super().__init__(name, column_name, **kw) + self.nullable = nullable + + +class ColumnType(AlterColumn): + def __init__( + self, name: str, column_name: str, type_: TypeEngine, **kw + ) -> None: + super().__init__(name, column_name, **kw) + self.type_ = sqltypes.to_instance(type_) + + +class ColumnName(AlterColumn): + def __init__( + self, name: str, column_name: str, newname: str, **kw + ) -> None: + super().__init__(name, column_name, **kw) + self.newname = newname + + +class ColumnDefault(AlterColumn): + def __init__( + self, + name: str, + column_name: str, + default: Optional[_ServerDefault], + **kw, + ) -> None: + super().__init__(name, column_name, **kw) + self.default = default + + +class ComputedColumnDefault(AlterColumn): + def __init__( + self, name: str, column_name: str, default: Optional[Computed], **kw + ) -> None: + super().__init__(name, column_name, **kw) + self.default = default + + +class IdentityColumnDefault(AlterColumn): + def __init__( + self, + name: str, + column_name: str, + default: Optional[Identity], + impl: DefaultImpl, + **kw, + ) -> None: + super().__init__(name, column_name, **kw) + self.default = default + self.impl = impl + + +class AddColumn(AlterTable): + def __init__( + self, + name: str, + column: Column[Any], + schema: Optional[Union[quoted_name, str]] = None, + ) -> None: + super().__init__(name, schema=schema) + self.column = column + + +class DropColumn(AlterTable): + def __init__( + self, name: str, column: Column[Any], schema: Optional[str] = None + ) -> None: + super().__init__(name, schema=schema) + self.column = column + + +class ColumnComment(AlterColumn): + def __init__( + self, name: str, column_name: str, comment: Optional[str], **kw + ) -> None: + super().__init__(name, column_name, **kw) + self.comment = comment + + +@compiles(RenameTable) # type: ignore[misc] +def visit_rename_table( + element: RenameTable, compiler: DDLCompiler, **kw +) -> str: + return "%s RENAME TO %s" % ( + alter_table(compiler, element.table_name, element.schema), + format_table_name(compiler, element.new_table_name, element.schema), + ) + + +@compiles(AddColumn) # type: ignore[misc] +def visit_add_column(element: AddColumn, compiler: DDLCompiler, **kw) -> str: + return "%s %s" % ( + alter_table(compiler, element.table_name, element.schema), + add_column(compiler, element.column, **kw), + ) + + +@compiles(DropColumn) # type: ignore[misc] +def visit_drop_column(element: DropColumn, compiler: DDLCompiler, **kw) -> str: + return "%s %s" % ( + alter_table(compiler, element.table_name, element.schema), + drop_column(compiler, element.column.name, **kw), + ) + + +@compiles(ColumnNullable) # type: ignore[misc] +def visit_column_nullable( + element: ColumnNullable, compiler: DDLCompiler, **kw +) -> str: + return "%s %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + alter_column(compiler, element.column_name), + "DROP NOT NULL" if element.nullable else "SET NOT NULL", + ) + + +@compiles(ColumnType) # type: ignore[misc] +def visit_column_type(element: ColumnType, compiler: DDLCompiler, **kw) -> str: + return "%s %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + alter_column(compiler, element.column_name), + "TYPE %s" % format_type(compiler, element.type_), + ) + + +@compiles(ColumnName) # type: ignore[misc] +def visit_column_name(element: ColumnName, compiler: DDLCompiler, **kw) -> str: + return "%s RENAME %s TO %s" % ( + alter_table(compiler, element.table_name, element.schema), + format_column_name(compiler, element.column_name), + format_column_name(compiler, element.newname), + ) + + +@compiles(ColumnDefault) # type: ignore[misc] +def visit_column_default( + element: ColumnDefault, compiler: DDLCompiler, **kw +) -> str: + return "%s %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + alter_column(compiler, element.column_name), + "SET DEFAULT %s" % format_server_default(compiler, element.default) + if element.default is not None + else "DROP DEFAULT", + ) + + +@compiles(ComputedColumnDefault) # type: ignore[misc] +def visit_computed_column( + element: ComputedColumnDefault, compiler: DDLCompiler, **kw +): + raise exc.CompileError( + 'Adding or removing a "computed" construct, e.g. GENERATED ' + "ALWAYS AS, to or from an existing column is not supported." + ) + + +@compiles(IdentityColumnDefault) # type: ignore[misc] +def visit_identity_column( + element: IdentityColumnDefault, compiler: DDLCompiler, **kw +): + raise exc.CompileError( + 'Adding, removing or modifying an "identity" construct, ' + "e.g. GENERATED AS IDENTITY, to or from an existing " + "column is not supported in this dialect." + ) + + +def quote_dotted( + name: Union[quoted_name, str], quote: functools.partial +) -> Union[quoted_name, str]: + """quote the elements of a dotted name""" + + if isinstance(name, quoted_name): + return quote(name) + result = ".".join([quote(x) for x in name.split(".")]) + return result + + +def format_table_name( + compiler: Compiled, + name: Union[quoted_name, str], + schema: Optional[Union[quoted_name, str]], +) -> Union[quoted_name, str]: + quote = functools.partial(compiler.preparer.quote) + if schema: + return quote_dotted(schema, quote) + "." + quote(name) + else: + return quote(name) + + +def format_column_name( + compiler: DDLCompiler, name: Optional[Union[quoted_name, str]] +) -> Union[quoted_name, str]: + return compiler.preparer.quote(name) # type: ignore[arg-type] + + +def format_server_default( + compiler: DDLCompiler, + default: Optional[_ServerDefault], +) -> str: + return compiler.get_column_default_string( + Column("x", Integer, server_default=default) + ) + + +def format_type(compiler: DDLCompiler, type_: TypeEngine) -> str: + return compiler.dialect.type_compiler.process(type_) + + +def alter_table( + compiler: DDLCompiler, + name: str, + schema: Optional[str], +) -> str: + return "ALTER TABLE %s" % format_table_name(compiler, name, schema) + + +def drop_column(compiler: DDLCompiler, name: str, **kw) -> str: + return "DROP COLUMN %s" % format_column_name(compiler, name) + + +def alter_column(compiler: DDLCompiler, name: str) -> str: + return "ALTER COLUMN %s" % format_column_name(compiler, name) + + +def add_column(compiler: DDLCompiler, column: Column[Any], **kw) -> str: + text = "ADD COLUMN %s" % compiler.get_column_specification(column, **kw) + + const = " ".join( + compiler.process(constraint) for constraint in column.constraints + ) + if const: + text += " " + const + + return text diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/impl.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/impl.py new file mode 100644 index 0000000000000000000000000000000000000000..2e4f1ae9405eac6c755f3f4f3957efa717ecd8da --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/impl.py @@ -0,0 +1,844 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +import logging +import re +from typing import Any +from typing import Callable +from typing import Dict +from typing import Iterable +from typing import List +from typing import Mapping +from typing import NamedTuple +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import Union + +from sqlalchemy import cast +from sqlalchemy import schema +from sqlalchemy import text + +from . import _autogen +from . import base +from ._autogen import _constraint_sig as _constraint_sig +from ._autogen import ComparisonResult as ComparisonResult +from .. import util +from ..util import sqla_compat + +if TYPE_CHECKING: + from typing import Literal + from typing import TextIO + + from sqlalchemy.engine import Connection + from sqlalchemy.engine import Dialect + from sqlalchemy.engine.cursor import CursorResult + from sqlalchemy.engine.reflection import Inspector + from sqlalchemy.sql import ClauseElement + from sqlalchemy.sql import Executable + from sqlalchemy.sql.elements import ColumnElement + from sqlalchemy.sql.elements import quoted_name + from sqlalchemy.sql.schema import Column + from sqlalchemy.sql.schema import Constraint + from sqlalchemy.sql.schema import ForeignKeyConstraint + from sqlalchemy.sql.schema import Index + from sqlalchemy.sql.schema import Table + from sqlalchemy.sql.schema import UniqueConstraint + from sqlalchemy.sql.selectable import TableClause + from sqlalchemy.sql.type_api import TypeEngine + + from .base import _ServerDefault + from ..autogenerate.api import AutogenContext + from ..operations.batch import ApplyBatchImpl + from ..operations.batch import BatchOperationsImpl + +log = logging.getLogger(__name__) + + +class ImplMeta(type): + def __init__( + cls, + classname: str, + bases: Tuple[Type[DefaultImpl]], + dict_: Dict[str, Any], + ): + newtype = type.__init__(cls, classname, bases, dict_) + if "__dialect__" in dict_: + _impls[dict_["__dialect__"]] = cls # type: ignore[assignment] + return newtype + + +_impls: Dict[str, Type[DefaultImpl]] = {} + + +class DefaultImpl(metaclass=ImplMeta): + + """Provide the entrypoint for major migration operations, + including database-specific behavioral variances. + + While individual SQL/DDL constructs already provide + for database-specific implementations, variances here + allow for entirely different sequences of operations + to take place for a particular migration, such as + SQL Server's special 'IDENTITY INSERT' step for + bulk inserts. + + """ + + __dialect__ = "default" + + transactional_ddl = False + command_terminator = ";" + type_synonyms: Tuple[Set[str], ...] = ({"NUMERIC", "DECIMAL"},) + type_arg_extract: Sequence[str] = () + # These attributes are deprecated in SQLAlchemy via #10247. They need to + # be ignored to support older version that did not use dialect kwargs. + # They only apply to Oracle and are replaced by oracle_order, + # oracle_on_null + identity_attrs_ignore: Tuple[str, ...] = ("order", "on_null") + + def __init__( + self, + dialect: Dialect, + connection: Optional[Connection], + as_sql: bool, + transactional_ddl: Optional[bool], + output_buffer: Optional[TextIO], + context_opts: Dict[str, Any], + ) -> None: + self.dialect = dialect + self.connection = connection + self.as_sql = as_sql + self.literal_binds = context_opts.get("literal_binds", False) + + self.output_buffer = output_buffer + self.memo: dict = {} + self.context_opts = context_opts + if transactional_ddl is not None: + self.transactional_ddl = transactional_ddl + + if self.literal_binds: + if not self.as_sql: + raise util.CommandError( + "Can't use literal_binds setting without as_sql mode" + ) + + @classmethod + def get_by_dialect(cls, dialect: Dialect) -> Type[DefaultImpl]: + return _impls[dialect.name] + + def static_output(self, text: str) -> None: + assert self.output_buffer is not None + self.output_buffer.write(text + "\n\n") + self.output_buffer.flush() + + def requires_recreate_in_batch( + self, batch_op: BatchOperationsImpl + ) -> bool: + """Return True if the given :class:`.BatchOperationsImpl` + would need the table to be recreated and copied in order to + proceed. + + Normally, only returns True on SQLite when operations other + than add_column are present. + + """ + return False + + def prep_table_for_batch( + self, batch_impl: ApplyBatchImpl, table: Table + ) -> None: + """perform any operations needed on a table before a new + one is created to replace it in batch mode. + + the PG dialect uses this to drop constraints on the table + before the new one uses those same names. + + """ + + @property + def bind(self) -> Optional[Connection]: + return self.connection + + def _exec( + self, + construct: Union[Executable, str], + execution_options: Optional[dict[str, Any]] = None, + multiparams: Sequence[dict] = (), + params: Dict[str, Any] = util.immutabledict(), + ) -> Optional[CursorResult]: + if isinstance(construct, str): + construct = text(construct) + if self.as_sql: + if multiparams or params: + # TODO: coverage + raise Exception("Execution arguments not allowed with as_sql") + + compile_kw: dict[str, Any] + if self.literal_binds and not isinstance( + construct, schema.DDLElement + ): + compile_kw = dict(compile_kwargs={"literal_binds": True}) + else: + compile_kw = {} + + if TYPE_CHECKING: + assert isinstance(construct, ClauseElement) + compiled = construct.compile(dialect=self.dialect, **compile_kw) + self.static_output( + str(compiled).replace("\t", " ").strip() + + self.command_terminator + ) + return None + else: + conn = self.connection + assert conn is not None + if execution_options: + conn = conn.execution_options(**execution_options) + if params: + assert isinstance(multiparams, tuple) + multiparams += (params,) + + return conn.execute(construct, multiparams) + + def execute( + self, + sql: Union[Executable, str], + execution_options: Optional[dict[str, Any]] = None, + ) -> None: + self._exec(sql, execution_options) + + def alter_column( + self, + table_name: str, + column_name: str, + nullable: Optional[bool] = None, + server_default: Union[_ServerDefault, Literal[False]] = False, + name: Optional[str] = None, + type_: Optional[TypeEngine] = None, + schema: Optional[str] = None, + autoincrement: Optional[bool] = None, + comment: Optional[Union[str, Literal[False]]] = False, + existing_comment: Optional[str] = None, + existing_type: Optional[TypeEngine] = None, + existing_server_default: Optional[_ServerDefault] = None, + existing_nullable: Optional[bool] = None, + existing_autoincrement: Optional[bool] = None, + **kw: Any, + ) -> None: + if autoincrement is not None or existing_autoincrement is not None: + util.warn( + "autoincrement and existing_autoincrement " + "only make sense for MySQL", + stacklevel=3, + ) + if nullable is not None: + self._exec( + base.ColumnNullable( + table_name, + column_name, + nullable, + schema=schema, + existing_type=existing_type, + existing_server_default=existing_server_default, + existing_nullable=existing_nullable, + existing_comment=existing_comment, + ) + ) + if server_default is not False: + kw = {} + cls_: Type[ + Union[ + base.ComputedColumnDefault, + base.IdentityColumnDefault, + base.ColumnDefault, + ] + ] + if sqla_compat._server_default_is_computed( + server_default, existing_server_default + ): + cls_ = base.ComputedColumnDefault + elif sqla_compat._server_default_is_identity( + server_default, existing_server_default + ): + cls_ = base.IdentityColumnDefault + kw["impl"] = self + else: + cls_ = base.ColumnDefault + self._exec( + cls_( + table_name, + column_name, + server_default, # type:ignore[arg-type] + schema=schema, + existing_type=existing_type, + existing_server_default=existing_server_default, + existing_nullable=existing_nullable, + existing_comment=existing_comment, + **kw, + ) + ) + if type_ is not None: + self._exec( + base.ColumnType( + table_name, + column_name, + type_, + schema=schema, + existing_type=existing_type, + existing_server_default=existing_server_default, + existing_nullable=existing_nullable, + existing_comment=existing_comment, + ) + ) + + if comment is not False: + self._exec( + base.ColumnComment( + table_name, + column_name, + comment, + schema=schema, + existing_type=existing_type, + existing_server_default=existing_server_default, + existing_nullable=existing_nullable, + existing_comment=existing_comment, + ) + ) + + # do the new name last ;) + if name is not None: + self._exec( + base.ColumnName( + table_name, + column_name, + name, + schema=schema, + existing_type=existing_type, + existing_server_default=existing_server_default, + existing_nullable=existing_nullable, + ) + ) + + def add_column( + self, + table_name: str, + column: Column[Any], + schema: Optional[Union[str, quoted_name]] = None, + ) -> None: + self._exec(base.AddColumn(table_name, column, schema=schema)) + + def drop_column( + self, + table_name: str, + column: Column[Any], + schema: Optional[str] = None, + **kw, + ) -> None: + self._exec(base.DropColumn(table_name, column, schema=schema)) + + def add_constraint(self, const: Any) -> None: + if const._create_rule is None or const._create_rule(self): + self._exec(schema.AddConstraint(const)) + + def drop_constraint(self, const: Constraint) -> None: + self._exec(schema.DropConstraint(const)) + + def rename_table( + self, + old_table_name: str, + new_table_name: Union[str, quoted_name], + schema: Optional[Union[str, quoted_name]] = None, + ) -> None: + self._exec( + base.RenameTable(old_table_name, new_table_name, schema=schema) + ) + + def create_table(self, table: Table) -> None: + table.dispatch.before_create( + table, self.connection, checkfirst=False, _ddl_runner=self + ) + self._exec(schema.CreateTable(table)) + table.dispatch.after_create( + table, self.connection, checkfirst=False, _ddl_runner=self + ) + for index in table.indexes: + self._exec(schema.CreateIndex(index)) + + with_comment = ( + self.dialect.supports_comments and not self.dialect.inline_comments + ) + comment = table.comment + if comment and with_comment: + self.create_table_comment(table) + + for column in table.columns: + comment = column.comment + if comment and with_comment: + self.create_column_comment(column) + + def drop_table(self, table: Table) -> None: + table.dispatch.before_drop( + table, self.connection, checkfirst=False, _ddl_runner=self + ) + self._exec(schema.DropTable(table)) + table.dispatch.after_drop( + table, self.connection, checkfirst=False, _ddl_runner=self + ) + + def create_index(self, index: Index, **kw: Any) -> None: + self._exec(schema.CreateIndex(index, **kw)) + + def create_table_comment(self, table: Table) -> None: + self._exec(schema.SetTableComment(table)) + + def drop_table_comment(self, table: Table) -> None: + self._exec(schema.DropTableComment(table)) + + def create_column_comment(self, column: ColumnElement[Any]) -> None: + self._exec(schema.SetColumnComment(column)) + + def drop_index(self, index: Index, **kw: Any) -> None: + self._exec(schema.DropIndex(index, **kw)) + + def bulk_insert( + self, + table: Union[TableClause, Table], + rows: List[dict], + multiinsert: bool = True, + ) -> None: + if not isinstance(rows, list): + raise TypeError("List expected") + elif rows and not isinstance(rows[0], dict): + raise TypeError("List of dictionaries expected") + if self.as_sql: + for row in rows: + self._exec( + sqla_compat._insert_inline(table).values( + **{ + k: sqla_compat._literal_bindparam( + k, v, type_=table.c[k].type + ) + if not isinstance( + v, sqla_compat._literal_bindparam + ) + else v + for k, v in row.items() + } + ) + ) + else: + if rows: + if multiinsert: + self._exec( + sqla_compat._insert_inline(table), multiparams=rows + ) + else: + for row in rows: + self._exec( + sqla_compat._insert_inline(table).values(**row) + ) + + def _tokenize_column_type(self, column: Column) -> Params: + definition: str + definition = self.dialect.type_compiler.process(column.type).lower() + + # tokenize the SQLAlchemy-generated version of a type, so that + # the two can be compared. + # + # examples: + # NUMERIC(10, 5) + # TIMESTAMP WITH TIMEZONE + # INTEGER UNSIGNED + # INTEGER (10) UNSIGNED + # INTEGER(10) UNSIGNED + # varchar character set utf8 + # + + tokens: List[str] = re.findall(r"[\w\-_]+|\(.+?\)", definition) + + term_tokens: List[str] = [] + paren_term = None + + for token in tokens: + if re.match(r"^\(.*\)$", token): + paren_term = token + else: + term_tokens.append(token) + + params = Params(term_tokens[0], term_tokens[1:], [], {}) + + if paren_term: + term: str + for term in re.findall("[^(),]+", paren_term): + if "=" in term: + key, val = term.split("=") + params.kwargs[key.strip()] = val.strip() + else: + params.args.append(term.strip()) + + return params + + def _column_types_match( + self, inspector_params: Params, metadata_params: Params + ) -> bool: + if inspector_params.token0 == metadata_params.token0: + return True + + synonyms = [{t.lower() for t in batch} for batch in self.type_synonyms] + inspector_all_terms = " ".join( + [inspector_params.token0] + inspector_params.tokens + ) + metadata_all_terms = " ".join( + [metadata_params.token0] + metadata_params.tokens + ) + + for batch in synonyms: + if {inspector_all_terms, metadata_all_terms}.issubset(batch) or { + inspector_params.token0, + metadata_params.token0, + }.issubset(batch): + return True + return False + + def _column_args_match( + self, inspected_params: Params, meta_params: Params + ) -> bool: + """We want to compare column parameters. However, we only want + to compare parameters that are set. If they both have `collation`, + we want to make sure they are the same. However, if only one + specifies it, dont flag it for being less specific + """ + + if ( + len(meta_params.tokens) == len(inspected_params.tokens) + and meta_params.tokens != inspected_params.tokens + ): + return False + + if ( + len(meta_params.args) == len(inspected_params.args) + and meta_params.args != inspected_params.args + ): + return False + + insp = " ".join(inspected_params.tokens).lower() + meta = " ".join(meta_params.tokens).lower() + + for reg in self.type_arg_extract: + mi = re.search(reg, insp) + mm = re.search(reg, meta) + + if mi and mm and mi.group(1) != mm.group(1): + return False + + return True + + def compare_type( + self, inspector_column: Column[Any], metadata_column: Column + ) -> bool: + """Returns True if there ARE differences between the types of the two + columns. Takes impl.type_synonyms into account between retrospected + and metadata types + """ + inspector_params = self._tokenize_column_type(inspector_column) + metadata_params = self._tokenize_column_type(metadata_column) + + if not self._column_types_match(inspector_params, metadata_params): + return True + if not self._column_args_match(inspector_params, metadata_params): + return True + return False + + def compare_server_default( + self, + inspector_column, + metadata_column, + rendered_metadata_default, + rendered_inspector_default, + ): + return rendered_inspector_default != rendered_metadata_default + + def correct_for_autogen_constraints( + self, + conn_uniques: Set[UniqueConstraint], + conn_indexes: Set[Index], + metadata_unique_constraints: Set[UniqueConstraint], + metadata_indexes: Set[Index], + ) -> None: + pass + + def cast_for_batch_migrate(self, existing, existing_transfer, new_type): + if existing.type._type_affinity is not new_type._type_affinity: + existing_transfer["expr"] = cast( + existing_transfer["expr"], new_type + ) + + def render_ddl_sql_expr( + self, expr: ClauseElement, is_server_default: bool = False, **kw: Any + ) -> str: + """Render a SQL expression that is typically a server default, + index expression, etc. + + """ + + compile_kw = {"literal_binds": True, "include_table": False} + + return str( + expr.compile(dialect=self.dialect, compile_kwargs=compile_kw) + ) + + def _compat_autogen_column_reflect(self, inspector: Inspector) -> Callable: + return self.autogen_column_reflect + + def correct_for_autogen_foreignkeys( + self, + conn_fks: Set[ForeignKeyConstraint], + metadata_fks: Set[ForeignKeyConstraint], + ) -> None: + pass + + def autogen_column_reflect(self, inspector, table, column_info): + """A hook that is attached to the 'column_reflect' event for when + a Table is reflected from the database during the autogenerate + process. + + Dialects can elect to modify the information gathered here. + + """ + + def start_migrations(self) -> None: + """A hook called when :meth:`.EnvironmentContext.run_migrations` + is called. + + Implementations can set up per-migration-run state here. + + """ + + def emit_begin(self) -> None: + """Emit the string ``BEGIN``, or the backend-specific + equivalent, on the current connection context. + + This is used in offline mode and typically + via :meth:`.EnvironmentContext.begin_transaction`. + + """ + self.static_output("BEGIN" + self.command_terminator) + + def emit_commit(self) -> None: + """Emit the string ``COMMIT``, or the backend-specific + equivalent, on the current connection context. + + This is used in offline mode and typically + via :meth:`.EnvironmentContext.begin_transaction`. + + """ + self.static_output("COMMIT" + self.command_terminator) + + def render_type( + self, type_obj: TypeEngine, autogen_context: AutogenContext + ) -> Union[str, Literal[False]]: + return False + + def _compare_identity_default(self, metadata_identity, inspector_identity): + # ignored contains the attributes that were not considered + # because assumed to their default values in the db. + diff, ignored = _compare_identity_options( + metadata_identity, + inspector_identity, + sqla_compat.Identity(), + skip={"always"}, + ) + + meta_always = getattr(metadata_identity, "always", None) + inspector_always = getattr(inspector_identity, "always", None) + # None and False are the same in this comparison + if bool(meta_always) != bool(inspector_always): + diff.add("always") + + diff.difference_update(self.identity_attrs_ignore) + + # returns 3 values: + return ( + # different identity attributes + diff, + # ignored identity attributes + ignored, + # if the two identity should be considered different + bool(diff) or bool(metadata_identity) != bool(inspector_identity), + ) + + def _compare_index_unique( + self, metadata_index: Index, reflected_index: Index + ) -> Optional[str]: + conn_unique = bool(reflected_index.unique) + meta_unique = bool(metadata_index.unique) + if conn_unique != meta_unique: + return f"unique={conn_unique} to unique={meta_unique}" + else: + return None + + def _create_metadata_constraint_sig( + self, constraint: _autogen._C, **opts: Any + ) -> _constraint_sig[_autogen._C]: + return _constraint_sig.from_constraint(True, self, constraint, **opts) + + def _create_reflected_constraint_sig( + self, constraint: _autogen._C, **opts: Any + ) -> _constraint_sig[_autogen._C]: + return _constraint_sig.from_constraint(False, self, constraint, **opts) + + def compare_indexes( + self, + metadata_index: Index, + reflected_index: Index, + ) -> ComparisonResult: + """Compare two indexes by comparing the signature generated by + ``create_index_sig``. + + This method returns a ``ComparisonResult``. + """ + msg: List[str] = [] + unique_msg = self._compare_index_unique( + metadata_index, reflected_index + ) + if unique_msg: + msg.append(unique_msg) + m_sig = self._create_metadata_constraint_sig(metadata_index) + r_sig = self._create_reflected_constraint_sig(reflected_index) + + assert _autogen.is_index_sig(m_sig) + assert _autogen.is_index_sig(r_sig) + + # The assumption is that the index have no expression + for sig in m_sig, r_sig: + if sig.has_expressions: + log.warning( + "Generating approximate signature for index %s. " + "The dialect " + "implementation should either skip expression indexes " + "or provide a custom implementation.", + sig.const, + ) + + if m_sig.column_names != r_sig.column_names: + msg.append( + f"expression {r_sig.column_names} to {m_sig.column_names}" + ) + + if msg: + return ComparisonResult.Different(msg) + else: + return ComparisonResult.Equal() + + def compare_unique_constraint( + self, + metadata_constraint: UniqueConstraint, + reflected_constraint: UniqueConstraint, + ) -> ComparisonResult: + """Compare two unique constraints by comparing the two signatures. + + The arguments are two tuples that contain the unique constraint and + the signatures generated by ``create_unique_constraint_sig``. + + This method returns a ``ComparisonResult``. + """ + metadata_tup = self._create_metadata_constraint_sig( + metadata_constraint + ) + reflected_tup = self._create_reflected_constraint_sig( + reflected_constraint + ) + + meta_sig = metadata_tup.unnamed + conn_sig = reflected_tup.unnamed + if conn_sig != meta_sig: + return ComparisonResult.Different( + f"expression {conn_sig} to {meta_sig}" + ) + else: + return ComparisonResult.Equal() + + def _skip_functional_indexes(self, metadata_indexes, conn_indexes): + conn_indexes_by_name = {c.name: c for c in conn_indexes} + + for idx in list(metadata_indexes): + if idx.name in conn_indexes_by_name: + continue + iex = sqla_compat.is_expression_index(idx) + if iex: + util.warn( + "autogenerate skipping metadata-specified " + "expression-based index " + f"{idx.name!r}; dialect {self.__dialect__!r} under " + f"SQLAlchemy {sqla_compat.sqlalchemy_version} can't " + "reflect these indexes so they can't be compared" + ) + metadata_indexes.discard(idx) + + def adjust_reflected_dialect_options( + self, reflected_object: Dict[str, Any], kind: str + ) -> Dict[str, Any]: + return reflected_object.get("dialect_options", {}) + + +class Params(NamedTuple): + token0: str + tokens: List[str] + args: List[str] + kwargs: Dict[str, str] + + +def _compare_identity_options( + metadata_io: Union[schema.Identity, schema.Sequence, None], + inspector_io: Union[schema.Identity, schema.Sequence, None], + default_io: Union[schema.Identity, schema.Sequence], + skip: Set[str], +): + # this can be used for identity or sequence compare. + # default_io is an instance of IdentityOption with all attributes to the + # default value. + meta_d = sqla_compat._get_identity_options_dict(metadata_io) + insp_d = sqla_compat._get_identity_options_dict(inspector_io) + + diff = set() + ignored_attr = set() + + def check_dicts( + meta_dict: Mapping[str, Any], + insp_dict: Mapping[str, Any], + default_dict: Mapping[str, Any], + attrs: Iterable[str], + ): + for attr in set(attrs).difference(skip): + meta_value = meta_dict.get(attr) + insp_value = insp_dict.get(attr) + if insp_value != meta_value: + default_value = default_dict.get(attr) + if meta_value == default_value: + ignored_attr.add(attr) + else: + diff.add(attr) + + check_dicts( + meta_d, + insp_d, + sqla_compat._get_identity_options_dict(default_io), + set(meta_d).union(insp_d), + ) + if sqla_compat.identity_has_dialect_kwargs: + # use only the dialect kwargs in inspector_io since metadata_io + # can have options for many backends + check_dicts( + getattr(metadata_io, "dialect_kwargs", {}), + getattr(inspector_io, "dialect_kwargs", {}), + default_io.dialect_kwargs, # type: ignore[union-attr] + getattr(inspector_io, "dialect_kwargs", {}), + ) + + return diff, ignored_attr diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/mssql.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/mssql.py new file mode 100644 index 0000000000000000000000000000000000000000..baa43d5e73abb3e40294c0000d0f2694182744eb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/mssql.py @@ -0,0 +1,419 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +import re +from typing import Any +from typing import Dict +from typing import List +from typing import Optional +from typing import TYPE_CHECKING +from typing import Union + +from sqlalchemy import types as sqltypes +from sqlalchemy.schema import Column +from sqlalchemy.schema import CreateIndex +from sqlalchemy.sql.base import Executable +from sqlalchemy.sql.elements import ClauseElement + +from .base import AddColumn +from .base import alter_column +from .base import alter_table +from .base import ColumnDefault +from .base import ColumnName +from .base import ColumnNullable +from .base import ColumnType +from .base import format_column_name +from .base import format_server_default +from .base import format_table_name +from .base import format_type +from .base import RenameTable +from .impl import DefaultImpl +from .. import util +from ..util import sqla_compat +from ..util.sqla_compat import compiles + +if TYPE_CHECKING: + from typing import Literal + + from sqlalchemy.dialects.mssql.base import MSDDLCompiler + from sqlalchemy.dialects.mssql.base import MSSQLCompiler + from sqlalchemy.engine.cursor import CursorResult + from sqlalchemy.sql.schema import Index + from sqlalchemy.sql.schema import Table + from sqlalchemy.sql.selectable import TableClause + from sqlalchemy.sql.type_api import TypeEngine + + from .base import _ServerDefault + + +class MSSQLImpl(DefaultImpl): + __dialect__ = "mssql" + transactional_ddl = True + batch_separator = "GO" + + type_synonyms = DefaultImpl.type_synonyms + ({"VARCHAR", "NVARCHAR"},) + identity_attrs_ignore = DefaultImpl.identity_attrs_ignore + ( + "minvalue", + "maxvalue", + "nominvalue", + "nomaxvalue", + "cycle", + "cache", + ) + + def __init__(self, *arg, **kw) -> None: + super().__init__(*arg, **kw) + self.batch_separator = self.context_opts.get( + "mssql_batch_separator", self.batch_separator + ) + + def _exec(self, construct: Any, *args, **kw) -> Optional[CursorResult]: + result = super()._exec(construct, *args, **kw) + if self.as_sql and self.batch_separator: + self.static_output(self.batch_separator) + return result + + def emit_begin(self) -> None: + self.static_output("BEGIN TRANSACTION" + self.command_terminator) + + def emit_commit(self) -> None: + super().emit_commit() + if self.as_sql and self.batch_separator: + self.static_output(self.batch_separator) + + def alter_column( # type:ignore[override] + self, + table_name: str, + column_name: str, + nullable: Optional[bool] = None, + server_default: Optional[ + Union[_ServerDefault, Literal[False]] + ] = False, + name: Optional[str] = None, + type_: Optional[TypeEngine] = None, + schema: Optional[str] = None, + existing_type: Optional[TypeEngine] = None, + existing_server_default: Optional[_ServerDefault] = None, + existing_nullable: Optional[bool] = None, + **kw: Any, + ) -> None: + if nullable is not None: + if type_ is not None: + # the NULL/NOT NULL alter will handle + # the type alteration + existing_type = type_ + type_ = None + elif existing_type is None: + raise util.CommandError( + "MS-SQL ALTER COLUMN operations " + "with NULL or NOT NULL require the " + "existing_type or a new type_ be passed." + ) + elif existing_nullable is not None and type_ is not None: + nullable = existing_nullable + + # the NULL/NOT NULL alter will handle + # the type alteration + existing_type = type_ + type_ = None + + elif type_ is not None: + util.warn( + "MS-SQL ALTER COLUMN operations that specify type_= " + "should also specify a nullable= or " + "existing_nullable= argument to avoid implicit conversion " + "of NOT NULL columns to NULL." + ) + + used_default = False + if sqla_compat._server_default_is_identity( + server_default, existing_server_default + ) or sqla_compat._server_default_is_computed( + server_default, existing_server_default + ): + used_default = True + kw["server_default"] = server_default + kw["existing_server_default"] = existing_server_default + + super().alter_column( + table_name, + column_name, + nullable=nullable, + type_=type_, + schema=schema, + existing_type=existing_type, + existing_nullable=existing_nullable, + **kw, + ) + + if server_default is not False and used_default is False: + if existing_server_default is not False or server_default is None: + self._exec( + _ExecDropConstraint( + table_name, + column_name, + "sys.default_constraints", + schema, + ) + ) + if server_default is not None: + super().alter_column( + table_name, + column_name, + schema=schema, + server_default=server_default, + ) + + if name is not None: + super().alter_column( + table_name, column_name, schema=schema, name=name + ) + + def create_index(self, index: Index, **kw: Any) -> None: + # this likely defaults to None if not present, so get() + # should normally not return the default value. being + # defensive in any case + mssql_include = index.kwargs.get("mssql_include", None) or () + assert index.table is not None + for col in mssql_include: + if col not in index.table.c: + index.table.append_column(Column(col, sqltypes.NullType)) + self._exec(CreateIndex(index, **kw)) + + def bulk_insert( # type:ignore[override] + self, table: Union[TableClause, Table], rows: List[dict], **kw: Any + ) -> None: + if self.as_sql: + self._exec( + "SET IDENTITY_INSERT %s ON" + % self.dialect.identifier_preparer.format_table(table) + ) + super().bulk_insert(table, rows, **kw) + self._exec( + "SET IDENTITY_INSERT %s OFF" + % self.dialect.identifier_preparer.format_table(table) + ) + else: + super().bulk_insert(table, rows, **kw) + + def drop_column( + self, + table_name: str, + column: Column[Any], + schema: Optional[str] = None, + **kw, + ) -> None: + drop_default = kw.pop("mssql_drop_default", False) + if drop_default: + self._exec( + _ExecDropConstraint( + table_name, column, "sys.default_constraints", schema + ) + ) + drop_check = kw.pop("mssql_drop_check", False) + if drop_check: + self._exec( + _ExecDropConstraint( + table_name, column, "sys.check_constraints", schema + ) + ) + drop_fks = kw.pop("mssql_drop_foreign_key", False) + if drop_fks: + self._exec(_ExecDropFKConstraint(table_name, column, schema)) + super().drop_column(table_name, column, schema=schema, **kw) + + def compare_server_default( + self, + inspector_column, + metadata_column, + rendered_metadata_default, + rendered_inspector_default, + ): + if rendered_metadata_default is not None: + rendered_metadata_default = re.sub( + r"[\(\) \"\']", "", rendered_metadata_default + ) + + if rendered_inspector_default is not None: + # SQL Server collapses whitespace and adds arbitrary parenthesis + # within expressions. our only option is collapse all of it + + rendered_inspector_default = re.sub( + r"[\(\) \"\']", "", rendered_inspector_default + ) + + return rendered_inspector_default != rendered_metadata_default + + def _compare_identity_default(self, metadata_identity, inspector_identity): + diff, ignored, is_alter = super()._compare_identity_default( + metadata_identity, inspector_identity + ) + + if ( + metadata_identity is None + and inspector_identity is not None + and not diff + and inspector_identity.column is not None + and inspector_identity.column.primary_key + ): + # mssql reflect primary keys with autoincrement as identity + # columns. if no different attributes are present ignore them + is_alter = False + + return diff, ignored, is_alter + + def adjust_reflected_dialect_options( + self, reflected_object: Dict[str, Any], kind: str + ) -> Dict[str, Any]: + options: Dict[str, Any] + options = reflected_object.get("dialect_options", {}).copy() + if not options.get("mssql_include"): + options.pop("mssql_include", None) + if not options.get("mssql_clustered"): + options.pop("mssql_clustered", None) + return options + + +class _ExecDropConstraint(Executable, ClauseElement): + inherit_cache = False + + def __init__( + self, + tname: str, + colname: Union[Column[Any], str], + type_: str, + schema: Optional[str], + ) -> None: + self.tname = tname + self.colname = colname + self.type_ = type_ + self.schema = schema + + +class _ExecDropFKConstraint(Executable, ClauseElement): + inherit_cache = False + + def __init__( + self, tname: str, colname: Column[Any], schema: Optional[str] + ) -> None: + self.tname = tname + self.colname = colname + self.schema = schema + + +@compiles(_ExecDropConstraint, "mssql") +def _exec_drop_col_constraint( + element: _ExecDropConstraint, compiler: MSSQLCompiler, **kw +) -> str: + schema, tname, colname, type_ = ( + element.schema, + element.tname, + element.colname, + element.type_, + ) + # from http://www.mssqltips.com/sqlservertip/1425/\ + # working-with-default-constraints-in-sql-server/ + return """declare @const_name varchar(256) +select @const_name = QUOTENAME([name]) from %(type)s +where parent_object_id = object_id('%(schema_dot)s%(tname)s') +and col_name(parent_object_id, parent_column_id) = '%(colname)s' +exec('alter table %(tname_quoted)s drop constraint ' + @const_name)""" % { + "type": type_, + "tname": tname, + "colname": colname, + "tname_quoted": format_table_name(compiler, tname, schema), + "schema_dot": schema + "." if schema else "", + } + + +@compiles(_ExecDropFKConstraint, "mssql") +def _exec_drop_col_fk_constraint( + element: _ExecDropFKConstraint, compiler: MSSQLCompiler, **kw +) -> str: + schema, tname, colname = element.schema, element.tname, element.colname + + return """declare @const_name varchar(256) +select @const_name = QUOTENAME([name]) from +sys.foreign_keys fk join sys.foreign_key_columns fkc +on fk.object_id=fkc.constraint_object_id +where fkc.parent_object_id = object_id('%(schema_dot)s%(tname)s') +and col_name(fkc.parent_object_id, fkc.parent_column_id) = '%(colname)s' +exec('alter table %(tname_quoted)s drop constraint ' + @const_name)""" % { + "tname": tname, + "colname": colname, + "tname_quoted": format_table_name(compiler, tname, schema), + "schema_dot": schema + "." if schema else "", + } + + +@compiles(AddColumn, "mssql") +def visit_add_column(element: AddColumn, compiler: MSDDLCompiler, **kw) -> str: + return "%s %s" % ( + alter_table(compiler, element.table_name, element.schema), + mssql_add_column(compiler, element.column, **kw), + ) + + +def mssql_add_column( + compiler: MSDDLCompiler, column: Column[Any], **kw +) -> str: + return "ADD %s" % compiler.get_column_specification(column, **kw) + + +@compiles(ColumnNullable, "mssql") +def visit_column_nullable( + element: ColumnNullable, compiler: MSDDLCompiler, **kw +) -> str: + return "%s %s %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + alter_column(compiler, element.column_name), + format_type(compiler, element.existing_type), # type: ignore[arg-type] + "NULL" if element.nullable else "NOT NULL", + ) + + +@compiles(ColumnDefault, "mssql") +def visit_column_default( + element: ColumnDefault, compiler: MSDDLCompiler, **kw +) -> str: + # TODO: there can also be a named constraint + # with ADD CONSTRAINT here + return "%s ADD DEFAULT %s FOR %s" % ( + alter_table(compiler, element.table_name, element.schema), + format_server_default(compiler, element.default), + format_column_name(compiler, element.column_name), + ) + + +@compiles(ColumnName, "mssql") +def visit_rename_column( + element: ColumnName, compiler: MSDDLCompiler, **kw +) -> str: + return "EXEC sp_rename '%s.%s', %s, 'COLUMN'" % ( + format_table_name(compiler, element.table_name, element.schema), + format_column_name(compiler, element.column_name), + format_column_name(compiler, element.newname), + ) + + +@compiles(ColumnType, "mssql") +def visit_column_type( + element: ColumnType, compiler: MSDDLCompiler, **kw +) -> str: + return "%s %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + alter_column(compiler, element.column_name), + format_type(compiler, element.type_), + ) + + +@compiles(RenameTable, "mssql") +def visit_rename_table( + element: RenameTable, compiler: MSDDLCompiler, **kw +) -> str: + return "EXEC sp_rename '%s', %s" % ( + format_table_name(compiler, element.table_name, element.schema), + format_table_name(compiler, element.new_table_name, None), + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/mysql.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/mysql.py new file mode 100644 index 0000000000000000000000000000000000000000..f312173e946d117b276e06ed5aa290f18f7db61b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/mysql.py @@ -0,0 +1,474 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +import re +from typing import Any +from typing import Optional +from typing import TYPE_CHECKING +from typing import Union + +from sqlalchemy import schema +from sqlalchemy import types as sqltypes + +from .base import alter_table +from .base import AlterColumn +from .base import ColumnDefault +from .base import ColumnName +from .base import ColumnNullable +from .base import ColumnType +from .base import format_column_name +from .base import format_server_default +from .impl import DefaultImpl +from .. import util +from ..util import sqla_compat +from ..util.sqla_compat import _is_mariadb +from ..util.sqla_compat import _is_type_bound +from ..util.sqla_compat import compiles + +if TYPE_CHECKING: + from typing import Literal + + from sqlalchemy.dialects.mysql.base import MySQLDDLCompiler + from sqlalchemy.sql.ddl import DropConstraint + from sqlalchemy.sql.schema import Constraint + from sqlalchemy.sql.type_api import TypeEngine + + from .base import _ServerDefault + + +class MySQLImpl(DefaultImpl): + __dialect__ = "mysql" + + transactional_ddl = False + type_synonyms = DefaultImpl.type_synonyms + ( + {"BOOL", "TINYINT"}, + {"JSON", "LONGTEXT"}, + ) + type_arg_extract = [r"character set ([\w\-_]+)", r"collate ([\w\-_]+)"] + + def alter_column( # type:ignore[override] + self, + table_name: str, + column_name: str, + nullable: Optional[bool] = None, + server_default: Union[_ServerDefault, Literal[False]] = False, + name: Optional[str] = None, + type_: Optional[TypeEngine] = None, + schema: Optional[str] = None, + existing_type: Optional[TypeEngine] = None, + existing_server_default: Optional[_ServerDefault] = None, + existing_nullable: Optional[bool] = None, + autoincrement: Optional[bool] = None, + existing_autoincrement: Optional[bool] = None, + comment: Optional[Union[str, Literal[False]]] = False, + existing_comment: Optional[str] = None, + **kw: Any, + ) -> None: + if sqla_compat._server_default_is_identity( + server_default, existing_server_default + ) or sqla_compat._server_default_is_computed( + server_default, existing_server_default + ): + # modifying computed or identity columns is not supported + # the default will raise + super().alter_column( + table_name, + column_name, + nullable=nullable, + type_=type_, + schema=schema, + existing_type=existing_type, + existing_nullable=existing_nullable, + server_default=server_default, + existing_server_default=existing_server_default, + **kw, + ) + if name is not None or self._is_mysql_allowed_functional_default( + type_ if type_ is not None else existing_type, server_default + ): + self._exec( + MySQLChangeColumn( + table_name, + column_name, + schema=schema, + newname=name if name is not None else column_name, + nullable=nullable + if nullable is not None + else existing_nullable + if existing_nullable is not None + else True, + type_=type_ if type_ is not None else existing_type, + default=server_default + if server_default is not False + else existing_server_default, + autoincrement=autoincrement + if autoincrement is not None + else existing_autoincrement, + comment=comment + if comment is not False + else existing_comment, + ) + ) + elif ( + nullable is not None + or type_ is not None + or autoincrement is not None + or comment is not False + ): + self._exec( + MySQLModifyColumn( + table_name, + column_name, + schema=schema, + newname=name if name is not None else column_name, + nullable=nullable + if nullable is not None + else existing_nullable + if existing_nullable is not None + else True, + type_=type_ if type_ is not None else existing_type, + default=server_default + if server_default is not False + else existing_server_default, + autoincrement=autoincrement + if autoincrement is not None + else existing_autoincrement, + comment=comment + if comment is not False + else existing_comment, + ) + ) + elif server_default is not False: + self._exec( + MySQLAlterDefault( + table_name, column_name, server_default, schema=schema + ) + ) + + def drop_constraint( + self, + const: Constraint, + ) -> None: + if isinstance(const, schema.CheckConstraint) and _is_type_bound(const): + return + + super().drop_constraint(const) + + def _is_mysql_allowed_functional_default( + self, + type_: Optional[TypeEngine], + server_default: Union[_ServerDefault, Literal[False]], + ) -> bool: + return ( + type_ is not None + and type_._type_affinity is sqltypes.DateTime + and server_default is not None + ) + + def compare_server_default( + self, + inspector_column, + metadata_column, + rendered_metadata_default, + rendered_inspector_default, + ): + # partially a workaround for SQLAlchemy issue #3023; if the + # column were created without "NOT NULL", MySQL may have added + # an implicit default of '0' which we need to skip + # TODO: this is not really covered anymore ? + if ( + metadata_column.type._type_affinity is sqltypes.Integer + and inspector_column.primary_key + and not inspector_column.autoincrement + and not rendered_metadata_default + and rendered_inspector_default == "'0'" + ): + return False + elif ( + rendered_inspector_default + and inspector_column.type._type_affinity is sqltypes.Integer + ): + rendered_inspector_default = ( + re.sub(r"^'|'$", "", rendered_inspector_default) + if rendered_inspector_default is not None + else None + ) + return rendered_inspector_default != rendered_metadata_default + elif ( + rendered_metadata_default + and metadata_column.type._type_affinity is sqltypes.String + ): + metadata_default = re.sub(r"^'|'$", "", rendered_metadata_default) + return rendered_inspector_default != f"'{metadata_default}'" + elif rendered_inspector_default and rendered_metadata_default: + # adjust for "function()" vs. "FUNCTION" as can occur particularly + # for the CURRENT_TIMESTAMP function on newer MariaDB versions + + # SQLAlchemy MySQL dialect bundles ON UPDATE into the server + # default; adjust for this possibly being present. + onupdate_ins = re.match( + r"(.*) (on update.*?)(?:\(\))?$", + rendered_inspector_default.lower(), + ) + onupdate_met = re.match( + r"(.*) (on update.*?)(?:\(\))?$", + rendered_metadata_default.lower(), + ) + + if onupdate_ins: + if not onupdate_met: + return True + elif onupdate_ins.group(2) != onupdate_met.group(2): + return True + + rendered_inspector_default = onupdate_ins.group(1) + rendered_metadata_default = onupdate_met.group(1) + + return re.sub( + r"(.*?)(?:\(\))?$", r"\1", rendered_inspector_default.lower() + ) != re.sub( + r"(.*?)(?:\(\))?$", r"\1", rendered_metadata_default.lower() + ) + else: + return rendered_inspector_default != rendered_metadata_default + + def correct_for_autogen_constraints( + self, + conn_unique_constraints, + conn_indexes, + metadata_unique_constraints, + metadata_indexes, + ): + # TODO: if SQLA 1.0, make use of "duplicates_index" + # metadata + removed = set() + for idx in list(conn_indexes): + if idx.unique: + continue + # MySQL puts implicit indexes on FK columns, even if + # composite and even if MyISAM, so can't check this too easily. + # the name of the index may be the column name or it may + # be the name of the FK constraint. + for col in idx.columns: + if idx.name == col.name: + conn_indexes.remove(idx) + removed.add(idx.name) + break + for fk in col.foreign_keys: + if fk.name == idx.name: + conn_indexes.remove(idx) + removed.add(idx.name) + break + if idx.name in removed: + break + + # then remove indexes from the "metadata_indexes" + # that we've removed from reflected, otherwise they come out + # as adds (see #202) + for idx in list(metadata_indexes): + if idx.name in removed: + metadata_indexes.remove(idx) + + def correct_for_autogen_foreignkeys(self, conn_fks, metadata_fks): + conn_fk_by_sig = { + self._create_reflected_constraint_sig(fk).unnamed_no_options: fk + for fk in conn_fks + } + metadata_fk_by_sig = { + self._create_metadata_constraint_sig(fk).unnamed_no_options: fk + for fk in metadata_fks + } + + for sig in set(conn_fk_by_sig).intersection(metadata_fk_by_sig): + mdfk = metadata_fk_by_sig[sig] + cnfk = conn_fk_by_sig[sig] + # MySQL considers RESTRICT to be the default and doesn't + # report on it. if the model has explicit RESTRICT and + # the conn FK has None, set it to RESTRICT + if ( + mdfk.ondelete is not None + and mdfk.ondelete.lower() == "restrict" + and cnfk.ondelete is None + ): + cnfk.ondelete = "RESTRICT" + if ( + mdfk.onupdate is not None + and mdfk.onupdate.lower() == "restrict" + and cnfk.onupdate is None + ): + cnfk.onupdate = "RESTRICT" + + +class MariaDBImpl(MySQLImpl): + __dialect__ = "mariadb" + + +class MySQLAlterDefault(AlterColumn): + def __init__( + self, + name: str, + column_name: str, + default: _ServerDefault, + schema: Optional[str] = None, + ) -> None: + super(AlterColumn, self).__init__(name, schema=schema) + self.column_name = column_name + self.default = default + + +class MySQLChangeColumn(AlterColumn): + def __init__( + self, + name: str, + column_name: str, + schema: Optional[str] = None, + newname: Optional[str] = None, + type_: Optional[TypeEngine] = None, + nullable: Optional[bool] = None, + default: Optional[Union[_ServerDefault, Literal[False]]] = False, + autoincrement: Optional[bool] = None, + comment: Optional[Union[str, Literal[False]]] = False, + ) -> None: + super(AlterColumn, self).__init__(name, schema=schema) + self.column_name = column_name + self.nullable = nullable + self.newname = newname + self.default = default + self.autoincrement = autoincrement + self.comment = comment + if type_ is None: + raise util.CommandError( + "All MySQL CHANGE/MODIFY COLUMN operations " + "require the existing type." + ) + + self.type_ = sqltypes.to_instance(type_) + + +class MySQLModifyColumn(MySQLChangeColumn): + pass + + +@compiles(ColumnNullable, "mysql", "mariadb") +@compiles(ColumnName, "mysql", "mariadb") +@compiles(ColumnDefault, "mysql", "mariadb") +@compiles(ColumnType, "mysql", "mariadb") +def _mysql_doesnt_support_individual(element, compiler, **kw): + raise NotImplementedError( + "Individual alter column constructs not supported by MySQL" + ) + + +@compiles(MySQLAlterDefault, "mysql", "mariadb") +def _mysql_alter_default( + element: MySQLAlterDefault, compiler: MySQLDDLCompiler, **kw +) -> str: + return "%s ALTER COLUMN %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + format_column_name(compiler, element.column_name), + "SET DEFAULT %s" % format_server_default(compiler, element.default) + if element.default is not None + else "DROP DEFAULT", + ) + + +@compiles(MySQLModifyColumn, "mysql", "mariadb") +def _mysql_modify_column( + element: MySQLModifyColumn, compiler: MySQLDDLCompiler, **kw +) -> str: + return "%s MODIFY %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + format_column_name(compiler, element.column_name), + _mysql_colspec( + compiler, + nullable=element.nullable, + server_default=element.default, + type_=element.type_, + autoincrement=element.autoincrement, + comment=element.comment, + ), + ) + + +@compiles(MySQLChangeColumn, "mysql", "mariadb") +def _mysql_change_column( + element: MySQLChangeColumn, compiler: MySQLDDLCompiler, **kw +) -> str: + return "%s CHANGE %s %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + format_column_name(compiler, element.column_name), + format_column_name(compiler, element.newname), + _mysql_colspec( + compiler, + nullable=element.nullable, + server_default=element.default, + type_=element.type_, + autoincrement=element.autoincrement, + comment=element.comment, + ), + ) + + +def _mysql_colspec( + compiler: MySQLDDLCompiler, + nullable: Optional[bool], + server_default: Optional[Union[_ServerDefault, Literal[False]]], + type_: TypeEngine, + autoincrement: Optional[bool], + comment: Optional[Union[str, Literal[False]]], +) -> str: + spec = "%s %s" % ( + compiler.dialect.type_compiler.process(type_), + "NULL" if nullable else "NOT NULL", + ) + if autoincrement: + spec += " AUTO_INCREMENT" + if server_default is not False and server_default is not None: + spec += " DEFAULT %s" % format_server_default(compiler, server_default) + if comment: + spec += " COMMENT %s" % compiler.sql_compiler.render_literal_value( + comment, sqltypes.String() + ) + + return spec + + +@compiles(schema.DropConstraint, "mysql", "mariadb") +def _mysql_drop_constraint( + element: DropConstraint, compiler: MySQLDDLCompiler, **kw +) -> str: + """Redefine SQLAlchemy's drop constraint to + raise errors for invalid constraint type.""" + + constraint = element.element + if isinstance( + constraint, + ( + schema.ForeignKeyConstraint, + schema.PrimaryKeyConstraint, + schema.UniqueConstraint, + ), + ): + assert not kw + return compiler.visit_drop_constraint(element) + elif isinstance(constraint, schema.CheckConstraint): + # note that SQLAlchemy as of 1.2 does not yet support + # DROP CONSTRAINT for MySQL/MariaDB, so we implement fully + # here. + if _is_mariadb(compiler.dialect): + return "ALTER TABLE %s DROP CONSTRAINT %s" % ( + compiler.preparer.format_table(constraint.table), + compiler.preparer.format_constraint(constraint), + ) + else: + return "ALTER TABLE %s DROP CHECK %s" % ( + compiler.preparer.format_table(constraint.table), + compiler.preparer.format_constraint(constraint), + ) + else: + raise NotImplementedError( + "No generic 'DROP CONSTRAINT' in MySQL - " + "please specify constraint type" + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/oracle.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..54011740723749b50f53beaac6c75ca020e365a3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/oracle.py @@ -0,0 +1,200 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +import re +from typing import Any +from typing import Optional +from typing import TYPE_CHECKING + +from sqlalchemy.sql import sqltypes + +from .base import AddColumn +from .base import alter_table +from .base import ColumnComment +from .base import ColumnDefault +from .base import ColumnName +from .base import ColumnNullable +from .base import ColumnType +from .base import format_column_name +from .base import format_server_default +from .base import format_table_name +from .base import format_type +from .base import IdentityColumnDefault +from .base import RenameTable +from .impl import DefaultImpl +from ..util.sqla_compat import compiles + +if TYPE_CHECKING: + from sqlalchemy.dialects.oracle.base import OracleDDLCompiler + from sqlalchemy.engine.cursor import CursorResult + from sqlalchemy.sql.schema import Column + + +class OracleImpl(DefaultImpl): + __dialect__ = "oracle" + transactional_ddl = False + batch_separator = "/" + command_terminator = "" + type_synonyms = DefaultImpl.type_synonyms + ( + {"VARCHAR", "VARCHAR2"}, + {"BIGINT", "INTEGER", "SMALLINT", "DECIMAL", "NUMERIC", "NUMBER"}, + {"DOUBLE", "FLOAT", "DOUBLE_PRECISION"}, + ) + identity_attrs_ignore = () + + def __init__(self, *arg, **kw) -> None: + super().__init__(*arg, **kw) + self.batch_separator = self.context_opts.get( + "oracle_batch_separator", self.batch_separator + ) + + def _exec(self, construct: Any, *args, **kw) -> Optional[CursorResult]: + result = super()._exec(construct, *args, **kw) + if self.as_sql and self.batch_separator: + self.static_output(self.batch_separator) + return result + + def compare_server_default( + self, + inspector_column, + metadata_column, + rendered_metadata_default, + rendered_inspector_default, + ): + if rendered_metadata_default is not None: + rendered_metadata_default = re.sub( + r"^\((.+)\)$", r"\1", rendered_metadata_default + ) + + rendered_metadata_default = re.sub( + r"^\"?'(.+)'\"?$", r"\1", rendered_metadata_default + ) + + if rendered_inspector_default is not None: + rendered_inspector_default = re.sub( + r"^\((.+)\)$", r"\1", rendered_inspector_default + ) + + rendered_inspector_default = re.sub( + r"^\"?'(.+)'\"?$", r"\1", rendered_inspector_default + ) + + rendered_inspector_default = rendered_inspector_default.strip() + return rendered_inspector_default != rendered_metadata_default + + def emit_begin(self) -> None: + self._exec("SET TRANSACTION READ WRITE") + + def emit_commit(self) -> None: + self._exec("COMMIT") + + +@compiles(AddColumn, "oracle") +def visit_add_column( + element: AddColumn, compiler: OracleDDLCompiler, **kw +) -> str: + return "%s %s" % ( + alter_table(compiler, element.table_name, element.schema), + add_column(compiler, element.column, **kw), + ) + + +@compiles(ColumnNullable, "oracle") +def visit_column_nullable( + element: ColumnNullable, compiler: OracleDDLCompiler, **kw +) -> str: + return "%s %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + alter_column(compiler, element.column_name), + "NULL" if element.nullable else "NOT NULL", + ) + + +@compiles(ColumnType, "oracle") +def visit_column_type( + element: ColumnType, compiler: OracleDDLCompiler, **kw +) -> str: + return "%s %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + alter_column(compiler, element.column_name), + "%s" % format_type(compiler, element.type_), + ) + + +@compiles(ColumnName, "oracle") +def visit_column_name( + element: ColumnName, compiler: OracleDDLCompiler, **kw +) -> str: + return "%s RENAME COLUMN %s TO %s" % ( + alter_table(compiler, element.table_name, element.schema), + format_column_name(compiler, element.column_name), + format_column_name(compiler, element.newname), + ) + + +@compiles(ColumnDefault, "oracle") +def visit_column_default( + element: ColumnDefault, compiler: OracleDDLCompiler, **kw +) -> str: + return "%s %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + alter_column(compiler, element.column_name), + "DEFAULT %s" % format_server_default(compiler, element.default) + if element.default is not None + else "DEFAULT NULL", + ) + + +@compiles(ColumnComment, "oracle") +def visit_column_comment( + element: ColumnComment, compiler: OracleDDLCompiler, **kw +) -> str: + ddl = "COMMENT ON COLUMN {table_name}.{column_name} IS {comment}" + + comment = compiler.sql_compiler.render_literal_value( + (element.comment if element.comment is not None else ""), + sqltypes.String(), + ) + + return ddl.format( + table_name=element.table_name, + column_name=element.column_name, + comment=comment, + ) + + +@compiles(RenameTable, "oracle") +def visit_rename_table( + element: RenameTable, compiler: OracleDDLCompiler, **kw +) -> str: + return "%s RENAME TO %s" % ( + alter_table(compiler, element.table_name, element.schema), + format_table_name(compiler, element.new_table_name, None), + ) + + +def alter_column(compiler: OracleDDLCompiler, name: str) -> str: + return "MODIFY %s" % format_column_name(compiler, name) + + +def add_column(compiler: OracleDDLCompiler, column: Column[Any], **kw) -> str: + return "ADD %s" % compiler.get_column_specification(column, **kw) + + +@compiles(IdentityColumnDefault, "oracle") +def visit_identity_column( + element: IdentityColumnDefault, compiler: OracleDDLCompiler, **kw +): + text = "%s %s " % ( + alter_table(compiler, element.table_name, element.schema), + alter_column(compiler, element.column_name), + ) + if element.default is None: + # drop identity + text += "DROP IDENTITY" + return text + else: + text += compiler.visit_identity_column(element.default) + return text diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/postgresql.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/postgresql.py new file mode 100644 index 0000000000000000000000000000000000000000..6507fcbdd75c82873e3fc4ff5e3030d8638c0474 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/postgresql.py @@ -0,0 +1,848 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +import logging +import re +from typing import Any +from typing import cast +from typing import Dict +from typing import List +from typing import Optional +from typing import Sequence +from typing import Tuple +from typing import TYPE_CHECKING +from typing import Union + +from sqlalchemy import Column +from sqlalchemy import literal_column +from sqlalchemy import Numeric +from sqlalchemy import text +from sqlalchemy import types as sqltypes +from sqlalchemy.dialects.postgresql import BIGINT +from sqlalchemy.dialects.postgresql import ExcludeConstraint +from sqlalchemy.dialects.postgresql import INTEGER +from sqlalchemy.schema import CreateIndex +from sqlalchemy.sql.elements import ColumnClause +from sqlalchemy.sql.elements import TextClause +from sqlalchemy.sql.functions import FunctionElement +from sqlalchemy.types import NULLTYPE + +from .base import alter_column +from .base import alter_table +from .base import AlterColumn +from .base import ColumnComment +from .base import format_column_name +from .base import format_table_name +from .base import format_type +from .base import IdentityColumnDefault +from .base import RenameTable +from .impl import ComparisonResult +from .impl import DefaultImpl +from .. import util +from ..autogenerate import render +from ..operations import ops +from ..operations import schemaobj +from ..operations.base import BatchOperations +from ..operations.base import Operations +from ..util import sqla_compat +from ..util.sqla_compat import compiles + +if TYPE_CHECKING: + from typing import Literal + + from sqlalchemy import Index + from sqlalchemy import UniqueConstraint + from sqlalchemy.dialects.postgresql.array import ARRAY + from sqlalchemy.dialects.postgresql.base import PGDDLCompiler + from sqlalchemy.dialects.postgresql.hstore import HSTORE + from sqlalchemy.dialects.postgresql.json import JSON + from sqlalchemy.dialects.postgresql.json import JSONB + from sqlalchemy.sql.elements import ClauseElement + from sqlalchemy.sql.elements import ColumnElement + from sqlalchemy.sql.elements import quoted_name + from sqlalchemy.sql.schema import MetaData + from sqlalchemy.sql.schema import Table + from sqlalchemy.sql.type_api import TypeEngine + + from .base import _ServerDefault + from ..autogenerate.api import AutogenContext + from ..autogenerate.render import _f_name + from ..runtime.migration import MigrationContext + + +log = logging.getLogger(__name__) + + +class PostgresqlImpl(DefaultImpl): + __dialect__ = "postgresql" + transactional_ddl = True + type_synonyms = DefaultImpl.type_synonyms + ( + {"FLOAT", "DOUBLE PRECISION"}, + ) + + def create_index(self, index: Index, **kw: Any) -> None: + # this likely defaults to None if not present, so get() + # should normally not return the default value. being + # defensive in any case + postgresql_include = index.kwargs.get("postgresql_include", None) or () + for col in postgresql_include: + if col not in index.table.c: # type: ignore[union-attr] + index.table.append_column( # type: ignore[union-attr] + Column(col, sqltypes.NullType) + ) + self._exec(CreateIndex(index, **kw)) + + def prep_table_for_batch(self, batch_impl, table): + for constraint in table.constraints: + if ( + constraint.name is not None + and constraint.name in batch_impl.named_constraints + ): + self.drop_constraint(constraint) + + def compare_server_default( + self, + inspector_column, + metadata_column, + rendered_metadata_default, + rendered_inspector_default, + ): + # don't do defaults for SERIAL columns + if ( + metadata_column.primary_key + and metadata_column is metadata_column.table._autoincrement_column + ): + return False + + conn_col_default = rendered_inspector_default + + defaults_equal = conn_col_default == rendered_metadata_default + if defaults_equal: + return False + + if None in ( + conn_col_default, + rendered_metadata_default, + metadata_column.server_default, + ): + return not defaults_equal + + metadata_default = metadata_column.server_default.arg + + if isinstance(metadata_default, str): + if not isinstance(inspector_column.type, Numeric): + metadata_default = re.sub(r"^'|'$", "", metadata_default) + metadata_default = f"'{metadata_default}'" + + metadata_default = literal_column(metadata_default) + + # run a real compare against the server + conn = self.connection + assert conn is not None + return not conn.scalar( + sqla_compat._select( + literal_column(conn_col_default) == metadata_default + ) + ) + + def alter_column( # type:ignore[override] + self, + table_name: str, + column_name: str, + nullable: Optional[bool] = None, + server_default: Union[_ServerDefault, Literal[False]] = False, + name: Optional[str] = None, + type_: Optional[TypeEngine] = None, + schema: Optional[str] = None, + autoincrement: Optional[bool] = None, + existing_type: Optional[TypeEngine] = None, + existing_server_default: Optional[_ServerDefault] = None, + existing_nullable: Optional[bool] = None, + existing_autoincrement: Optional[bool] = None, + **kw: Any, + ) -> None: + using = kw.pop("postgresql_using", None) + + if using is not None and type_ is None: + raise util.CommandError( + "postgresql_using must be used with the type_ parameter" + ) + + if type_ is not None: + self._exec( + PostgresqlColumnType( + table_name, + column_name, + type_, + schema=schema, + using=using, + existing_type=existing_type, + existing_server_default=existing_server_default, + existing_nullable=existing_nullable, + ) + ) + + super().alter_column( + table_name, + column_name, + nullable=nullable, + server_default=server_default, + name=name, + schema=schema, + autoincrement=autoincrement, + existing_type=existing_type, + existing_server_default=existing_server_default, + existing_nullable=existing_nullable, + existing_autoincrement=existing_autoincrement, + **kw, + ) + + def autogen_column_reflect(self, inspector, table, column_info): + if column_info.get("default") and isinstance( + column_info["type"], (INTEGER, BIGINT) + ): + seq_match = re.match( + r"nextval\('(.+?)'::regclass\)", column_info["default"] + ) + if seq_match: + info = sqla_compat._exec_on_inspector( + inspector, + text( + "select c.relname, a.attname " + "from pg_class as c join " + "pg_depend d on d.objid=c.oid and " + "d.classid='pg_class'::regclass and " + "d.refclassid='pg_class'::regclass " + "join pg_class t on t.oid=d.refobjid " + "join pg_attribute a on a.attrelid=t.oid and " + "a.attnum=d.refobjsubid " + "where c.relkind='S' and c.relname=:seqname" + ), + seqname=seq_match.group(1), + ).first() + if info: + seqname, colname = info + if colname == column_info["name"]: + log.info( + "Detected sequence named '%s' as " + "owned by integer column '%s(%s)', " + "assuming SERIAL and omitting", + seqname, + table.name, + colname, + ) + # sequence, and the owner is this column, + # its a SERIAL - whack it! + del column_info["default"] + + def correct_for_autogen_constraints( + self, + conn_unique_constraints, + conn_indexes, + metadata_unique_constraints, + metadata_indexes, + ): + doubled_constraints = { + index + for index in conn_indexes + if index.info.get("duplicates_constraint") + } + + for ix in doubled_constraints: + conn_indexes.remove(ix) + + if not sqla_compat.sqla_2: + self._skip_functional_indexes(metadata_indexes, conn_indexes) + + # pg behavior regarding modifiers + # | # | compiled sql | returned sql | regexp. group is removed | + # | - | ---------------- | -----------------| ------------------------ | + # | 1 | nulls first | nulls first | - | + # | 2 | nulls last | | (? str: + expr = expr.lower().replace('"', "").replace("'", "") + if index.table is not None: + # should not be needed, since include_table=False is in compile + expr = expr.replace(f"{index.table.name.lower()}.", "") + + if "::" in expr: + # strip :: cast. types can have spaces in them + expr = re.sub(r"(::[\w ]+\w)", "", expr) + + while expr and expr[0] == "(" and expr[-1] == ")": + expr = expr[1:-1] + + # NOTE: when parsing the connection expression this cleanup could + # be skipped + for rs in self._default_modifiers_re: + if match := rs.search(expr): + start, end = match.span(1) + expr = expr[:start] + expr[end:] + break + + while expr and expr[0] == "(" and expr[-1] == ")": + expr = expr[1:-1] + + # strip casts + cast_re = re.compile(r"cast\s*\(") + if cast_re.match(expr): + expr = cast_re.sub("", expr) + # remove the as type + expr = re.sub(r"as\s+[^)]+\)", "", expr) + # remove spaces + expr = expr.replace(" ", "") + return expr + + def _dialect_options( + self, item: Union[Index, UniqueConstraint] + ) -> Tuple[Any, ...]: + # only the positive case is returned by sqlalchemy reflection so + # None and False are threated the same + if item.dialect_kwargs.get("postgresql_nulls_not_distinct"): + return ("nulls_not_distinct",) + return () + + def compare_indexes( + self, + metadata_index: Index, + reflected_index: Index, + ) -> ComparisonResult: + msg = [] + unique_msg = self._compare_index_unique( + metadata_index, reflected_index + ) + if unique_msg: + msg.append(unique_msg) + m_exprs = metadata_index.expressions + r_exprs = reflected_index.expressions + if len(m_exprs) != len(r_exprs): + msg.append(f"expression number {len(r_exprs)} to {len(m_exprs)}") + if msg: + # no point going further, return early + return ComparisonResult.Different(msg) + skip = [] + for pos, (m_e, r_e) in enumerate(zip(m_exprs, r_exprs), 1): + m_compile = self._compile_element(m_e) + m_text = self._cleanup_index_expr(metadata_index, m_compile) + # print(f"META ORIG: {m_compile!r} CLEANUP: {m_text!r}") + r_compile = self._compile_element(r_e) + r_text = self._cleanup_index_expr(metadata_index, r_compile) + # print(f"CONN ORIG: {r_compile!r} CLEANUP: {r_text!r}") + if m_text == r_text: + continue # expressions these are equal + elif m_compile.strip().endswith("_ops") and ( + " " in m_compile or ")" in m_compile # is an expression + ): + skip.append( + f"expression #{pos} {m_compile!r} detected " + "as including operator clause." + ) + util.warn( + f"Expression #{pos} {m_compile!r} in index " + f"{reflected_index.name!r} detected to include " + "an operator clause. Expression compare cannot proceed. " + "Please move the operator clause to the " + "``postgresql_ops`` dict to enable proper compare " + "of the index expressions: " + "https://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#operator-classes", # noqa: E501 + ) + else: + msg.append(f"expression #{pos} {r_compile!r} to {m_compile!r}") + + m_options = self._dialect_options(metadata_index) + r_options = self._dialect_options(reflected_index) + if m_options != r_options: + msg.extend(f"options {r_options} to {m_options}") + + if msg: + return ComparisonResult.Different(msg) + elif skip: + # if there are other changes detected don't skip the index + return ComparisonResult.Skip(skip) + else: + return ComparisonResult.Equal() + + def compare_unique_constraint( + self, + metadata_constraint: UniqueConstraint, + reflected_constraint: UniqueConstraint, + ) -> ComparisonResult: + metadata_tup = self._create_metadata_constraint_sig( + metadata_constraint + ) + reflected_tup = self._create_reflected_constraint_sig( + reflected_constraint + ) + + meta_sig = metadata_tup.unnamed + conn_sig = reflected_tup.unnamed + if conn_sig != meta_sig: + return ComparisonResult.Different( + f"expression {conn_sig} to {meta_sig}" + ) + + metadata_do = self._dialect_options(metadata_tup.const) + conn_do = self._dialect_options(reflected_tup.const) + if metadata_do != conn_do: + return ComparisonResult.Different( + f"expression {conn_do} to {metadata_do}" + ) + + return ComparisonResult.Equal() + + def adjust_reflected_dialect_options( + self, reflected_options: Dict[str, Any], kind: str + ) -> Dict[str, Any]: + options: Dict[str, Any] + options = reflected_options.get("dialect_options", {}).copy() + if not options.get("postgresql_include"): + options.pop("postgresql_include", None) + return options + + def _compile_element(self, element: Union[ClauseElement, str]) -> str: + if isinstance(element, str): + return element + return element.compile( + dialect=self.dialect, + compile_kwargs={"literal_binds": True, "include_table": False}, + ).string + + def render_ddl_sql_expr( + self, + expr: ClauseElement, + is_server_default: bool = False, + is_index: bool = False, + **kw: Any, + ) -> str: + """Render a SQL expression that is typically a server default, + index expression, etc. + + """ + + # apply self_group to index expressions; + # see https://github.com/sqlalchemy/sqlalchemy/blob/ + # 82fa95cfce070fab401d020c6e6e4a6a96cc2578/ + # lib/sqlalchemy/dialects/postgresql/base.py#L2261 + if is_index and not isinstance(expr, ColumnClause): + expr = expr.self_group() + + return super().render_ddl_sql_expr( + expr, is_server_default=is_server_default, is_index=is_index, **kw + ) + + def render_type( + self, type_: TypeEngine, autogen_context: AutogenContext + ) -> Union[str, Literal[False]]: + mod = type(type_).__module__ + if not mod.startswith("sqlalchemy.dialects.postgresql"): + return False + + if hasattr(self, "_render_%s_type" % type_.__visit_name__): + meth = getattr(self, "_render_%s_type" % type_.__visit_name__) + return meth(type_, autogen_context) + + return False + + def _render_HSTORE_type( + self, type_: HSTORE, autogen_context: AutogenContext + ) -> str: + return cast( + str, + render._render_type_w_subtype( + type_, autogen_context, "text_type", r"(.+?\(.*text_type=)" + ), + ) + + def _render_ARRAY_type( + self, type_: ARRAY, autogen_context: AutogenContext + ) -> str: + return cast( + str, + render._render_type_w_subtype( + type_, autogen_context, "item_type", r"(.+?\()" + ), + ) + + def _render_JSON_type( + self, type_: JSON, autogen_context: AutogenContext + ) -> str: + return cast( + str, + render._render_type_w_subtype( + type_, autogen_context, "astext_type", r"(.+?\(.*astext_type=)" + ), + ) + + def _render_JSONB_type( + self, type_: JSONB, autogen_context: AutogenContext + ) -> str: + return cast( + str, + render._render_type_w_subtype( + type_, autogen_context, "astext_type", r"(.+?\(.*astext_type=)" + ), + ) + + +class PostgresqlColumnType(AlterColumn): + def __init__( + self, name: str, column_name: str, type_: TypeEngine, **kw + ) -> None: + using = kw.pop("using", None) + super().__init__(name, column_name, **kw) + self.type_ = sqltypes.to_instance(type_) + self.using = using + + +@compiles(RenameTable, "postgresql") +def visit_rename_table( + element: RenameTable, compiler: PGDDLCompiler, **kw +) -> str: + return "%s RENAME TO %s" % ( + alter_table(compiler, element.table_name, element.schema), + format_table_name(compiler, element.new_table_name, None), + ) + + +@compiles(PostgresqlColumnType, "postgresql") +def visit_column_type( + element: PostgresqlColumnType, compiler: PGDDLCompiler, **kw +) -> str: + return "%s %s %s %s" % ( + alter_table(compiler, element.table_name, element.schema), + alter_column(compiler, element.column_name), + "TYPE %s" % format_type(compiler, element.type_), + "USING %s" % element.using if element.using else "", + ) + + +@compiles(ColumnComment, "postgresql") +def visit_column_comment( + element: ColumnComment, compiler: PGDDLCompiler, **kw +) -> str: + ddl = "COMMENT ON COLUMN {table_name}.{column_name} IS {comment}" + comment = ( + compiler.sql_compiler.render_literal_value( + element.comment, sqltypes.String() + ) + if element.comment is not None + else "NULL" + ) + + return ddl.format( + table_name=format_table_name( + compiler, element.table_name, element.schema + ), + column_name=format_column_name(compiler, element.column_name), + comment=comment, + ) + + +@compiles(IdentityColumnDefault, "postgresql") +def visit_identity_column( + element: IdentityColumnDefault, compiler: PGDDLCompiler, **kw +): + text = "%s %s " % ( + alter_table(compiler, element.table_name, element.schema), + alter_column(compiler, element.column_name), + ) + if element.default is None: + # drop identity + text += "DROP IDENTITY" + return text + elif element.existing_server_default is None: + # add identity options + text += "ADD " + text += compiler.visit_identity_column(element.default) + return text + else: + # alter identity + diff, _, _ = element.impl._compare_identity_default( + element.default, element.existing_server_default + ) + identity = element.default + for attr in sorted(diff): + if attr == "always": + text += "SET GENERATED %s " % ( + "ALWAYS" if identity.always else "BY DEFAULT" + ) + else: + text += "SET %s " % compiler.get_identity_options( + sqla_compat.Identity(**{attr: getattr(identity, attr)}) + ) + return text + + +@Operations.register_operation("create_exclude_constraint") +@BatchOperations.register_operation( + "create_exclude_constraint", "batch_create_exclude_constraint" +) +@ops.AddConstraintOp.register_add_constraint("exclude_constraint") +class CreateExcludeConstraintOp(ops.AddConstraintOp): + """Represent a create exclude constraint operation.""" + + constraint_type = "exclude" + + def __init__( + self, + constraint_name: sqla_compat._ConstraintName, + table_name: Union[str, quoted_name], + elements: Union[ + Sequence[Tuple[str, str]], + Sequence[Tuple[ColumnClause[Any], str]], + ], + where: Optional[Union[ColumnElement[bool], str]] = None, + schema: Optional[str] = None, + _orig_constraint: Optional[ExcludeConstraint] = None, + **kw, + ) -> None: + self.constraint_name = constraint_name + self.table_name = table_name + self.elements = elements + self.where = where + self.schema = schema + self._orig_constraint = _orig_constraint + self.kw = kw + + @classmethod + def from_constraint( # type:ignore[override] + cls, constraint: ExcludeConstraint + ) -> CreateExcludeConstraintOp: + constraint_table = sqla_compat._table_for_constraint(constraint) + return cls( + constraint.name, + constraint_table.name, + [ # type: ignore + (expr, op) for expr, name, op in constraint._render_exprs + ], + where=cast("ColumnElement[bool] | None", constraint.where), + schema=constraint_table.schema, + _orig_constraint=constraint, + deferrable=constraint.deferrable, + initially=constraint.initially, + using=constraint.using, + ) + + def to_constraint( + self, migration_context: Optional[MigrationContext] = None + ) -> ExcludeConstraint: + if self._orig_constraint is not None: + return self._orig_constraint + schema_obj = schemaobj.SchemaObjects(migration_context) + t = schema_obj.table(self.table_name, schema=self.schema) + excl = ExcludeConstraint( + *self.elements, + name=self.constraint_name, + where=self.where, + **self.kw, + ) + for ( + expr, + name, + oper, + ) in excl._render_exprs: + t.append_column(Column(name, NULLTYPE)) + t.append_constraint(excl) + return excl + + @classmethod + def create_exclude_constraint( + cls, + operations: Operations, + constraint_name: str, + table_name: str, + *elements: Any, + **kw: Any, + ) -> Optional[Table]: + """Issue an alter to create an EXCLUDE constraint using the + current migration context. + + .. note:: This method is Postgresql specific, and additionally + requires at least SQLAlchemy 1.0. + + e.g.:: + + from alembic import op + + op.create_exclude_constraint( + "user_excl", + "user", + ("period", "&&"), + ("group", "="), + where=("group != 'some group'"), + ) + + Note that the expressions work the same way as that of + the ``ExcludeConstraint`` object itself; if plain strings are + passed, quoting rules must be applied manually. + + :param name: Name of the constraint. + :param table_name: String name of the source table. + :param elements: exclude conditions. + :param where: SQL expression or SQL string with optional WHERE + clause. + :param deferrable: optional bool. If set, emit DEFERRABLE or + NOT DEFERRABLE when issuing DDL for this constraint. + :param initially: optional string. If set, emit INITIALLY + when issuing DDL for this constraint. + :param schema: Optional schema name to operate within. + + """ + op = cls(constraint_name, table_name, elements, **kw) + return operations.invoke(op) + + @classmethod + def batch_create_exclude_constraint( + cls, + operations: BatchOperations, + constraint_name: str, + *elements: Any, + **kw: Any, + ) -> Optional[Table]: + """Issue a "create exclude constraint" instruction using the + current batch migration context. + + .. note:: This method is Postgresql specific, and additionally + requires at least SQLAlchemy 1.0. + + .. seealso:: + + :meth:`.Operations.create_exclude_constraint` + + """ + kw["schema"] = operations.impl.schema + op = cls(constraint_name, operations.impl.table_name, elements, **kw) + return operations.invoke(op) + + +@render.renderers.dispatch_for(CreateExcludeConstraintOp) +def _add_exclude_constraint( + autogen_context: AutogenContext, op: CreateExcludeConstraintOp +) -> str: + return _exclude_constraint(op.to_constraint(), autogen_context, alter=True) + + +@render._constraint_renderers.dispatch_for(ExcludeConstraint) +def _render_inline_exclude_constraint( + constraint: ExcludeConstraint, + autogen_context: AutogenContext, + namespace_metadata: MetaData, +) -> str: + rendered = render._user_defined_render( + "exclude", constraint, autogen_context + ) + if rendered is not False: + return rendered + + return _exclude_constraint(constraint, autogen_context, False) + + +def _postgresql_autogenerate_prefix(autogen_context: AutogenContext) -> str: + imports = autogen_context.imports + if imports is not None: + imports.add("from sqlalchemy.dialects import postgresql") + return "postgresql." + + +def _exclude_constraint( + constraint: ExcludeConstraint, + autogen_context: AutogenContext, + alter: bool, +) -> str: + opts: List[Tuple[str, Union[quoted_name, str, _f_name, None]]] = [] + + has_batch = autogen_context._has_batch + + if constraint.deferrable: + opts.append(("deferrable", str(constraint.deferrable))) + if constraint.initially: + opts.append(("initially", str(constraint.initially))) + if constraint.using: + opts.append(("using", str(constraint.using))) + if not has_batch and alter and constraint.table.schema: + opts.append(("schema", render._ident(constraint.table.schema))) + if not alter and constraint.name: + opts.append( + ("name", render._render_gen_name(autogen_context, constraint.name)) + ) + + def do_expr_where_opts(): + args = [ + "(%s, %r)" + % ( + _render_potential_column( + sqltext, # type:ignore[arg-type] + autogen_context, + ), + opstring, + ) + for sqltext, name, opstring in constraint._render_exprs + ] + if constraint.where is not None: + args.append( + "where=%s" + % render._render_potential_expr( + constraint.where, autogen_context + ) + ) + args.extend(["%s=%r" % (k, v) for k, v in opts]) + return args + + if alter: + args = [ + repr(render._render_gen_name(autogen_context, constraint.name)) + ] + if not has_batch: + args += [repr(render._ident(constraint.table.name))] + args.extend(do_expr_where_opts()) + return "%(prefix)screate_exclude_constraint(%(args)s)" % { + "prefix": render._alembic_autogenerate_prefix(autogen_context), + "args": ", ".join(args), + } + else: + args = do_expr_where_opts() + return "%(prefix)sExcludeConstraint(%(args)s)" % { + "prefix": _postgresql_autogenerate_prefix(autogen_context), + "args": ", ".join(args), + } + + +def _render_potential_column( + value: Union[ + ColumnClause[Any], Column[Any], TextClause, FunctionElement[Any] + ], + autogen_context: AutogenContext, +) -> str: + if isinstance(value, ColumnClause): + if value.is_literal: + # like literal_column("int8range(from, to)") in ExcludeConstraint + template = "%(prefix)sliteral_column(%(name)r)" + else: + template = "%(prefix)scolumn(%(name)r)" + + return template % { + "prefix": render._sqlalchemy_autogenerate_prefix(autogen_context), + "name": value.name, + } + else: + return render._render_potential_expr( + value, + autogen_context, + wrap_in_text=isinstance(value, (TextClause, FunctionElement)), + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/sqlite.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/sqlite.py new file mode 100644 index 0000000000000000000000000000000000000000..762e8ca198a6af4d001afd362ff15ac9c43a2821 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/ddl/sqlite.py @@ -0,0 +1,225 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +import re +from typing import Any +from typing import Dict +from typing import Optional +from typing import TYPE_CHECKING +from typing import Union + +from sqlalchemy import cast +from sqlalchemy import JSON +from sqlalchemy import schema +from sqlalchemy import sql + +from .base import alter_table +from .base import format_table_name +from .base import RenameTable +from .impl import DefaultImpl +from .. import util +from ..util.sqla_compat import compiles + +if TYPE_CHECKING: + from sqlalchemy.engine.reflection import Inspector + from sqlalchemy.sql.compiler import DDLCompiler + from sqlalchemy.sql.elements import Cast + from sqlalchemy.sql.elements import ClauseElement + from sqlalchemy.sql.schema import Column + from sqlalchemy.sql.schema import Constraint + from sqlalchemy.sql.schema import Table + from sqlalchemy.sql.type_api import TypeEngine + + from ..operations.batch import BatchOperationsImpl + + +class SQLiteImpl(DefaultImpl): + __dialect__ = "sqlite" + + transactional_ddl = False + """SQLite supports transactional DDL, but pysqlite does not: + see: http://bugs.python.org/issue10740 + """ + + def requires_recreate_in_batch( + self, batch_op: BatchOperationsImpl + ) -> bool: + """Return True if the given :class:`.BatchOperationsImpl` + would need the table to be recreated and copied in order to + proceed. + + Normally, only returns True on SQLite when operations other + than add_column are present. + + """ + for op in batch_op.batch: + if op[0] == "add_column": + col = op[1][1] + if isinstance( + col.server_default, schema.DefaultClause + ) and isinstance(col.server_default.arg, sql.ClauseElement): + return True + elif ( + isinstance(col.server_default, util.sqla_compat.Computed) + and col.server_default.persisted + ): + return True + elif op[0] not in ("create_index", "drop_index"): + return True + else: + return False + + def add_constraint(self, const: Constraint): + # attempt to distinguish between an + # auto-gen constraint and an explicit one + if const._create_rule is None: + raise NotImplementedError( + "No support for ALTER of constraints in SQLite dialect. " + "Please refer to the batch mode feature which allows for " + "SQLite migrations using a copy-and-move strategy." + ) + elif const._create_rule(self): + util.warn( + "Skipping unsupported ALTER for " + "creation of implicit constraint. " + "Please refer to the batch mode feature which allows for " + "SQLite migrations using a copy-and-move strategy." + ) + + def drop_constraint(self, const: Constraint): + if const._create_rule is None: + raise NotImplementedError( + "No support for ALTER of constraints in SQLite dialect. " + "Please refer to the batch mode feature which allows for " + "SQLite migrations using a copy-and-move strategy." + ) + + def compare_server_default( + self, + inspector_column: Column[Any], + metadata_column: Column[Any], + rendered_metadata_default: Optional[str], + rendered_inspector_default: Optional[str], + ) -> bool: + if rendered_metadata_default is not None: + rendered_metadata_default = re.sub( + r"^\((.+)\)$", r"\1", rendered_metadata_default + ) + + rendered_metadata_default = re.sub( + r"^\"?'(.+)'\"?$", r"\1", rendered_metadata_default + ) + + if rendered_inspector_default is not None: + rendered_inspector_default = re.sub( + r"^\((.+)\)$", r"\1", rendered_inspector_default + ) + + rendered_inspector_default = re.sub( + r"^\"?'(.+)'\"?$", r"\1", rendered_inspector_default + ) + + return rendered_inspector_default != rendered_metadata_default + + def _guess_if_default_is_unparenthesized_sql_expr( + self, expr: Optional[str] + ) -> bool: + """Determine if a server default is a SQL expression or a constant. + + There are too many assertions that expect server defaults to round-trip + identically without parenthesis added so we will add parens only in + very specific cases. + + """ + if not expr: + return False + elif re.match(r"^[0-9\.]$", expr): + return False + elif re.match(r"^'.+'$", expr): + return False + elif re.match(r"^\(.+\)$", expr): + return False + else: + return True + + def autogen_column_reflect( + self, + inspector: Inspector, + table: Table, + column_info: Dict[str, Any], + ) -> None: + # SQLite expression defaults require parenthesis when sent + # as DDL + if self._guess_if_default_is_unparenthesized_sql_expr( + column_info.get("default", None) + ): + column_info["default"] = "(%s)" % (column_info["default"],) + + def render_ddl_sql_expr( + self, expr: ClauseElement, is_server_default: bool = False, **kw + ) -> str: + # SQLite expression defaults require parenthesis when sent + # as DDL + str_expr = super().render_ddl_sql_expr( + expr, is_server_default=is_server_default, **kw + ) + + if ( + is_server_default + and self._guess_if_default_is_unparenthesized_sql_expr(str_expr) + ): + str_expr = "(%s)" % (str_expr,) + return str_expr + + def cast_for_batch_migrate( + self, + existing: Column[Any], + existing_transfer: Dict[str, Union[TypeEngine, Cast]], + new_type: TypeEngine, + ) -> None: + if ( + existing.type._type_affinity is not new_type._type_affinity + and not isinstance(new_type, JSON) + ): + existing_transfer["expr"] = cast( + existing_transfer["expr"], new_type + ) + + def correct_for_autogen_constraints( + self, + conn_unique_constraints, + conn_indexes, + metadata_unique_constraints, + metadata_indexes, + ): + self._skip_functional_indexes(metadata_indexes, conn_indexes) + + +@compiles(RenameTable, "sqlite") +def visit_rename_table( + element: RenameTable, compiler: DDLCompiler, **kw +) -> str: + return "%s RENAME TO %s" % ( + alter_table(compiler, element.table_name, element.schema), + format_table_name(compiler, element.new_table_name, None), + ) + + +# @compiles(AddColumn, 'sqlite') +# def visit_add_column(element, compiler, **kw): +# return "%s %s" % ( +# alter_table(compiler, element.table_name, element.schema), +# add_column(compiler, element.column, **kw) +# ) + + +# def add_column(compiler, column, **kw): +# text = "ADD COLUMN %s" % compiler.get_column_specification(column, **kw) +# need to modify SQLAlchemy so that the CHECK associated with a Boolean +# or Enum gets placed as part of the column constraints, not the Table +# see ticket 98 +# for const in column.constraints: +# text += compiler.process(AddConstraint(const)) +# return text diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..26197cbe8205decca224757d329e634a6a23d2e2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/__init__.py @@ -0,0 +1,15 @@ +from . import toimpl +from .base import AbstractOperations +from .base import BatchOperations +from .base import Operations +from .ops import MigrateOperation +from .ops import MigrationScript + + +__all__ = [ + "AbstractOperations", + "Operations", + "BatchOperations", + "MigrateOperation", + "MigrationScript", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/base.py new file mode 100644 index 0000000000000000000000000000000000000000..bafe441a69ceb2bcd13f5f3f3fad1382b589e99f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/base.py @@ -0,0 +1,1893 @@ +# mypy: allow-untyped-calls + +from __future__ import annotations + +from contextlib import contextmanager +import re +import textwrap +from typing import Any +from typing import Awaitable +from typing import Callable +from typing import Dict +from typing import Iterator +from typing import List # noqa +from typing import Mapping +from typing import NoReturn +from typing import Optional +from typing import overload +from typing import Sequence # noqa +from typing import Tuple +from typing import Type # noqa +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from sqlalchemy.sql.elements import conv + +from . import batch +from . import schemaobj +from .. import util +from ..util import sqla_compat +from ..util.compat import formatannotation_fwdref +from ..util.compat import inspect_formatargspec +from ..util.compat import inspect_getfullargspec +from ..util.sqla_compat import _literal_bindparam + + +if TYPE_CHECKING: + from typing import Literal + + from sqlalchemy import Table + from sqlalchemy.engine import Connection + from sqlalchemy.sql import Executable + from sqlalchemy.sql.expression import ColumnElement + from sqlalchemy.sql.expression import TableClause + from sqlalchemy.sql.expression import TextClause + from sqlalchemy.sql.functions import Function + from sqlalchemy.sql.schema import Column + from sqlalchemy.sql.schema import Computed + from sqlalchemy.sql.schema import Identity + from sqlalchemy.sql.schema import SchemaItem + from sqlalchemy.types import TypeEngine + + from .batch import BatchOperationsImpl + from .ops import AddColumnOp + from .ops import AddConstraintOp + from .ops import AlterColumnOp + from .ops import AlterTableOp + from .ops import BulkInsertOp + from .ops import CreateIndexOp + from .ops import CreateTableCommentOp + from .ops import CreateTableOp + from .ops import DropColumnOp + from .ops import DropConstraintOp + from .ops import DropIndexOp + from .ops import DropTableCommentOp + from .ops import DropTableOp + from .ops import ExecuteSQLOp + from .ops import MigrateOperation + from ..ddl import DefaultImpl + from ..runtime.migration import MigrationContext +__all__ = ("Operations", "BatchOperations") +_T = TypeVar("_T") + +_C = TypeVar("_C", bound=Callable[..., Any]) + + +class AbstractOperations(util.ModuleClsProxy): + """Base class for Operations and BatchOperations. + + .. versionadded:: 1.11.0 + + """ + + impl: Union[DefaultImpl, BatchOperationsImpl] + _to_impl = util.Dispatcher() + + def __init__( + self, + migration_context: MigrationContext, + impl: Optional[BatchOperationsImpl] = None, + ) -> None: + """Construct a new :class:`.Operations` + + :param migration_context: a :class:`.MigrationContext` + instance. + + """ + self.migration_context = migration_context + if impl is None: + self.impl = migration_context.impl + else: + self.impl = impl + + self.schema_obj = schemaobj.SchemaObjects(migration_context) + + @classmethod + def register_operation( + cls, name: str, sourcename: Optional[str] = None + ) -> Callable[[Type[_T]], Type[_T]]: + """Register a new operation for this class. + + This method is normally used to add new operations + to the :class:`.Operations` class, and possibly the + :class:`.BatchOperations` class as well. All Alembic migration + operations are implemented via this system, however the system + is also available as a public API to facilitate adding custom + operations. + + .. seealso:: + + :ref:`operation_plugins` + + + """ + + def register(op_cls: Type[_T]) -> Type[_T]: + if sourcename is None: + fn = getattr(op_cls, name) + source_name = fn.__name__ + else: + fn = getattr(op_cls, sourcename) + source_name = fn.__name__ + + spec = inspect_getfullargspec(fn) + + name_args = spec[0] + assert name_args[0:2] == ["cls", "operations"] + + name_args[0:2] = ["self"] + + args = inspect_formatargspec( + *spec, formatannotation=formatannotation_fwdref + ) + num_defaults = len(spec[3]) if spec[3] else 0 + + defaulted_vals: Tuple[Any, ...] + + if num_defaults: + defaulted_vals = tuple(name_args[0 - num_defaults :]) + else: + defaulted_vals = () + + defaulted_vals += tuple(spec[4]) + # here, we are using formatargspec in a different way in order + # to get a string that will re-apply incoming arguments to a new + # function call + + apply_kw = inspect_formatargspec( + name_args + spec[4], + spec[1], + spec[2], + defaulted_vals, + formatvalue=lambda x: "=" + x, + formatannotation=formatannotation_fwdref, + ) + + args = re.sub( + r'[_]?ForwardRef\(([\'"].+?[\'"])\)', + lambda m: m.group(1), + args, + ) + + func_text = textwrap.dedent( + """\ + def %(name)s%(args)s: + %(doc)r + return op_cls.%(source_name)s%(apply_kw)s + """ + % { + "name": name, + "source_name": source_name, + "args": args, + "apply_kw": apply_kw, + "doc": fn.__doc__, + } + ) + + globals_ = dict(globals()) + globals_.update({"op_cls": op_cls}) + lcl: Dict[str, Any] = {} + + exec(func_text, globals_, lcl) + setattr(cls, name, lcl[name]) + fn.__func__.__doc__ = ( + "This method is proxied on " + "the :class:`.%s` class, via the :meth:`.%s.%s` method." + % (cls.__name__, cls.__name__, name) + ) + if hasattr(fn, "_legacy_translations"): + lcl[name]._legacy_translations = fn._legacy_translations + return op_cls + + return register + + @classmethod + def implementation_for(cls, op_cls: Any) -> Callable[[_C], _C]: + """Register an implementation for a given :class:`.MigrateOperation`. + + This is part of the operation extensibility API. + + .. seealso:: + + :ref:`operation_plugins` - example of use + + """ + + def decorate(fn: _C) -> _C: + cls._to_impl.dispatch_for(op_cls)(fn) + return fn + + return decorate + + @classmethod + @contextmanager + def context( + cls, migration_context: MigrationContext + ) -> Iterator[Operations]: + op = Operations(migration_context) + op._install_proxy() + yield op + op._remove_proxy() + + @contextmanager + def batch_alter_table( + self, + table_name: str, + schema: Optional[str] = None, + recreate: Literal["auto", "always", "never"] = "auto", + partial_reordering: Optional[Tuple[Any, ...]] = None, + copy_from: Optional[Table] = None, + table_args: Tuple[Any, ...] = (), + table_kwargs: Mapping[str, Any] = util.immutabledict(), + reflect_args: Tuple[Any, ...] = (), + reflect_kwargs: Mapping[str, Any] = util.immutabledict(), + naming_convention: Optional[Dict[str, str]] = None, + ) -> Iterator[BatchOperations]: + """Invoke a series of per-table migrations in batch. + + Batch mode allows a series of operations specific to a table + to be syntactically grouped together, and allows for alternate + modes of table migration, in particular the "recreate" style of + migration required by SQLite. + + "recreate" style is as follows: + + 1. A new table is created with the new specification, based on the + migration directives within the batch, using a temporary name. + + 2. the data copied from the existing table to the new table. + + 3. the existing table is dropped. + + 4. the new table is renamed to the existing table name. + + The directive by default will only use "recreate" style on the + SQLite backend, and only if directives are present which require + this form, e.g. anything other than ``add_column()``. The batch + operation on other backends will proceed using standard ALTER TABLE + operations. + + The method is used as a context manager, which returns an instance + of :class:`.BatchOperations`; this object is the same as + :class:`.Operations` except that table names and schema names + are omitted. E.g.:: + + with op.batch_alter_table("some_table") as batch_op: + batch_op.add_column(Column("foo", Integer)) + batch_op.drop_column("bar") + + The operations within the context manager are invoked at once + when the context is ended. When run against SQLite, if the + migrations include operations not supported by SQLite's ALTER TABLE, + the entire table will be copied to a new one with the new + specification, moving all data across as well. + + The copy operation by default uses reflection to retrieve the current + structure of the table, and therefore :meth:`.batch_alter_table` + in this mode requires that the migration is run in "online" mode. + The ``copy_from`` parameter may be passed which refers to an existing + :class:`.Table` object, which will bypass this reflection step. + + .. note:: The table copy operation will currently not copy + CHECK constraints, and may not copy UNIQUE constraints that are + unnamed, as is possible on SQLite. See the section + :ref:`sqlite_batch_constraints` for workarounds. + + :param table_name: name of table + :param schema: optional schema name. + :param recreate: under what circumstances the table should be + recreated. At its default of ``"auto"``, the SQLite dialect will + recreate the table if any operations other than ``add_column()``, + ``create_index()``, or ``drop_index()`` are + present. Other options include ``"always"`` and ``"never"``. + :param copy_from: optional :class:`~sqlalchemy.schema.Table` object + that will act as the structure of the table being copied. If omitted, + table reflection is used to retrieve the structure of the table. + + .. seealso:: + + :ref:`batch_offline_mode` + + :paramref:`~.Operations.batch_alter_table.reflect_args` + + :paramref:`~.Operations.batch_alter_table.reflect_kwargs` + + :param reflect_args: a sequence of additional positional arguments that + will be applied to the table structure being reflected / copied; + this may be used to pass column and constraint overrides to the + table that will be reflected, in lieu of passing the whole + :class:`~sqlalchemy.schema.Table` using + :paramref:`~.Operations.batch_alter_table.copy_from`. + :param reflect_kwargs: a dictionary of additional keyword arguments + that will be applied to the table structure being copied; this may be + used to pass additional table and reflection options to the table that + will be reflected, in lieu of passing the whole + :class:`~sqlalchemy.schema.Table` using + :paramref:`~.Operations.batch_alter_table.copy_from`. + :param table_args: a sequence of additional positional arguments that + will be applied to the new :class:`~sqlalchemy.schema.Table` when + created, in addition to those copied from the source table. + This may be used to provide additional constraints such as CHECK + constraints that may not be reflected. + :param table_kwargs: a dictionary of additional keyword arguments + that will be applied to the new :class:`~sqlalchemy.schema.Table` + when created, in addition to those copied from the source table. + This may be used to provide for additional table options that may + not be reflected. + :param naming_convention: a naming convention dictionary of the form + described at :ref:`autogen_naming_conventions` which will be applied + to the :class:`~sqlalchemy.schema.MetaData` during the reflection + process. This is typically required if one wants to drop SQLite + constraints, as these constraints will not have names when + reflected on this backend. Requires SQLAlchemy **0.9.4** or greater. + + .. seealso:: + + :ref:`dropping_sqlite_foreign_keys` + + :param partial_reordering: a list of tuples, each suggesting a desired + ordering of two or more columns in the newly created table. Requires + that :paramref:`.batch_alter_table.recreate` is set to ``"always"``. + Examples, given a table with columns "a", "b", "c", and "d": + + Specify the order of all columns:: + + with op.batch_alter_table( + "some_table", + recreate="always", + partial_reordering=[("c", "d", "a", "b")], + ) as batch_op: + pass + + Ensure "d" appears before "c", and "b", appears before "a":: + + with op.batch_alter_table( + "some_table", + recreate="always", + partial_reordering=[("d", "c"), ("b", "a")], + ) as batch_op: + pass + + The ordering of columns not included in the partial_reordering + set is undefined. Therefore it is best to specify the complete + ordering of all columns for best results. + + .. note:: batch mode requires SQLAlchemy 0.8 or above. + + .. seealso:: + + :ref:`batch_migrations` + + """ + impl = batch.BatchOperationsImpl( + self, + table_name, + schema, + recreate, + copy_from, + table_args, + table_kwargs, + reflect_args, + reflect_kwargs, + naming_convention, + partial_reordering, + ) + batch_op = BatchOperations(self.migration_context, impl=impl) + yield batch_op + impl.flush() + + def get_context(self) -> MigrationContext: + """Return the :class:`.MigrationContext` object that's + currently in use. + + """ + + return self.migration_context + + @overload + def invoke(self, operation: CreateTableOp) -> Table: + ... + + @overload + def invoke( + self, + operation: Union[ + AddConstraintOp, + DropConstraintOp, + CreateIndexOp, + DropIndexOp, + AddColumnOp, + AlterColumnOp, + AlterTableOp, + CreateTableCommentOp, + DropTableCommentOp, + DropColumnOp, + BulkInsertOp, + DropTableOp, + ExecuteSQLOp, + ], + ) -> None: + ... + + @overload + def invoke(self, operation: MigrateOperation) -> Any: + ... + + def invoke(self, operation: MigrateOperation) -> Any: + """Given a :class:`.MigrateOperation`, invoke it in terms of + this :class:`.Operations` instance. + + """ + fn = self._to_impl.dispatch( + operation, self.migration_context.impl.__dialect__ + ) + return fn(self, operation) + + def f(self, name: str) -> conv: + """Indicate a string name that has already had a naming convention + applied to it. + + This feature combines with the SQLAlchemy ``naming_convention`` feature + to disambiguate constraint names that have already had naming + conventions applied to them, versus those that have not. This is + necessary in the case that the ``"%(constraint_name)s"`` token + is used within a naming convention, so that it can be identified + that this particular name should remain fixed. + + If the :meth:`.Operations.f` is used on a constraint, the naming + convention will not take effect:: + + op.add_column("t", "x", Boolean(name=op.f("ck_bool_t_x"))) + + Above, the CHECK constraint generated will have the name + ``ck_bool_t_x`` regardless of whether or not a naming convention is + in use. + + Alternatively, if a naming convention is in use, and 'f' is not used, + names will be converted along conventions. If the ``target_metadata`` + contains the naming convention + ``{"ck": "ck_bool_%(table_name)s_%(constraint_name)s"}``, then the + output of the following: + + op.add_column("t", "x", Boolean(name="x")) + + will be:: + + CONSTRAINT ck_bool_t_x CHECK (x in (1, 0))) + + The function is rendered in the output of autogenerate when + a particular constraint name is already converted. + + """ + return conv(name) + + def inline_literal( + self, value: Union[str, int], type_: Optional[TypeEngine[Any]] = None + ) -> _literal_bindparam: + r"""Produce an 'inline literal' expression, suitable for + using in an INSERT, UPDATE, or DELETE statement. + + When using Alembic in "offline" mode, CRUD operations + aren't compatible with SQLAlchemy's default behavior surrounding + literal values, + which is that they are converted into bound values and passed + separately into the ``execute()`` method of the DBAPI cursor. + An offline SQL + script needs to have these rendered inline. While it should + always be noted that inline literal values are an **enormous** + security hole in an application that handles untrusted input, + a schema migration is not run in this context, so + literals are safe to render inline, with the caveat that + advanced types like dates may not be supported directly + by SQLAlchemy. + + See :meth:`.Operations.execute` for an example usage of + :meth:`.Operations.inline_literal`. + + The environment can also be configured to attempt to render + "literal" values inline automatically, for those simple types + that are supported by the dialect; see + :paramref:`.EnvironmentContext.configure.literal_binds` for this + more recently added feature. + + :param value: The value to render. Strings, integers, and simple + numerics should be supported. Other types like boolean, + dates, etc. may or may not be supported yet by various + backends. + :param type\_: optional - a :class:`sqlalchemy.types.TypeEngine` + subclass stating the type of this value. In SQLAlchemy + expressions, this is usually derived automatically + from the Python type of the value itself, as well as + based on the context in which the value is used. + + .. seealso:: + + :paramref:`.EnvironmentContext.configure.literal_binds` + + """ + return sqla_compat._literal_bindparam(None, value, type_=type_) + + def get_bind(self) -> Connection: + """Return the current 'bind'. + + Under normal circumstances, this is the + :class:`~sqlalchemy.engine.Connection` currently being used + to emit SQL to the database. + + In a SQL script context, this value is ``None``. [TODO: verify this] + + """ + return self.migration_context.impl.bind # type: ignore[return-value] + + def run_async( + self, + async_function: Callable[..., Awaitable[_T]], + *args: Any, + **kw_args: Any, + ) -> _T: + """Invoke the given asynchronous callable, passing an asynchronous + :class:`~sqlalchemy.ext.asyncio.AsyncConnection` as the first + argument. + + This method allows calling async functions from within the + synchronous ``upgrade()`` or ``downgrade()`` alembic migration + method. + + The async connection passed to the callable shares the same + transaction as the connection running in the migration context. + + Any additional arg or kw_arg passed to this function are passed + to the provided async function. + + .. versionadded: 1.11 + + .. note:: + + This method can be called only when alembic is called using + an async dialect. + """ + if not sqla_compat.sqla_14_18: + raise NotImplementedError("SQLAlchemy 1.4.18+ required") + sync_conn = self.get_bind() + if sync_conn is None: + raise NotImplementedError("Cannot call run_async in SQL mode") + if not sync_conn.dialect.is_async: + raise ValueError("Cannot call run_async with a sync engine") + from sqlalchemy.ext.asyncio import AsyncConnection + from sqlalchemy.util import await_only + + async_conn = AsyncConnection._retrieve_proxy_for_target(sync_conn) + return await_only(async_function(async_conn, *args, **kw_args)) + + +class Operations(AbstractOperations): + """Define high level migration operations. + + Each operation corresponds to some schema migration operation, + executed against a particular :class:`.MigrationContext` + which in turn represents connectivity to a database, + or a file output stream. + + While :class:`.Operations` is normally configured as + part of the :meth:`.EnvironmentContext.run_migrations` + method called from an ``env.py`` script, a standalone + :class:`.Operations` instance can be + made for use cases external to regular Alembic + migrations by passing in a :class:`.MigrationContext`:: + + from alembic.migration import MigrationContext + from alembic.operations import Operations + + conn = myengine.connect() + ctx = MigrationContext.configure(conn) + op = Operations(ctx) + + op.alter_column("t", "c", nullable=True) + + Note that as of 0.8, most of the methods on this class are produced + dynamically using the :meth:`.Operations.register_operation` + method. + + """ + + if TYPE_CHECKING: + # START STUB FUNCTIONS: op_cls + # ### the following stubs are generated by tools/write_pyi.py ### + # ### do not edit ### + + def add_column( + self, + table_name: str, + column: Column[Any], + *, + schema: Optional[str] = None, + ) -> None: + """Issue an "add column" instruction using the current + migration context. + + e.g.:: + + from alembic import op + from sqlalchemy import Column, String + + op.add_column("organization", Column("name", String())) + + The :meth:`.Operations.add_column` method typically corresponds + to the SQL command "ALTER TABLE... ADD COLUMN". Within the scope + of this command, the column's name, datatype, nullability, + and optional server-generated defaults may be indicated. + + .. note:: + + With the exception of NOT NULL constraints or single-column FOREIGN + KEY constraints, other kinds of constraints such as PRIMARY KEY, + UNIQUE or CHECK constraints **cannot** be generated using this + method; for these constraints, refer to operations such as + :meth:`.Operations.create_primary_key` and + :meth:`.Operations.create_check_constraint`. In particular, the + following :class:`~sqlalchemy.schema.Column` parameters are + **ignored**: + + * :paramref:`~sqlalchemy.schema.Column.primary_key` - SQL databases + typically do not support an ALTER operation that can add + individual columns one at a time to an existing primary key + constraint, therefore it's less ambiguous to use the + :meth:`.Operations.create_primary_key` method, which assumes no + existing primary key constraint is present. + * :paramref:`~sqlalchemy.schema.Column.unique` - use the + :meth:`.Operations.create_unique_constraint` method + * :paramref:`~sqlalchemy.schema.Column.index` - use the + :meth:`.Operations.create_index` method + + + The provided :class:`~sqlalchemy.schema.Column` object may include a + :class:`~sqlalchemy.schema.ForeignKey` constraint directive, + referencing a remote table name. For this specific type of constraint, + Alembic will automatically emit a second ALTER statement in order to + add the single-column FOREIGN KEY constraint separately:: + + from alembic import op + from sqlalchemy import Column, INTEGER, ForeignKey + + op.add_column( + "organization", + Column("account_id", INTEGER, ForeignKey("accounts.id")), + ) + + The column argument passed to :meth:`.Operations.add_column` is a + :class:`~sqlalchemy.schema.Column` construct, used in the same way it's + used in SQLAlchemy. In particular, values or functions to be indicated + as producing the column's default value on the database side are + specified using the ``server_default`` parameter, and not ``default`` + which only specifies Python-side defaults:: + + from alembic import op + from sqlalchemy import Column, TIMESTAMP, func + + # specify "DEFAULT NOW" along with the column add + op.add_column( + "account", + Column("timestamp", TIMESTAMP, server_default=func.now()), + ) + + :param table_name: String name of the parent table. + :param column: a :class:`sqlalchemy.schema.Column` object + representing the new column. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ # noqa: E501 + ... + + def alter_column( + self, + table_name: str, + column_name: str, + *, + nullable: Optional[bool] = None, + comment: Union[str, Literal[False], None] = False, + server_default: Any = False, + new_column_name: Optional[str] = None, + type_: Union[TypeEngine[Any], Type[TypeEngine[Any]], None] = None, + existing_type: Union[ + TypeEngine[Any], Type[TypeEngine[Any]], None + ] = None, + existing_server_default: Union[ + str, bool, Identity, Computed, None + ] = False, + existing_nullable: Optional[bool] = None, + existing_comment: Optional[str] = None, + schema: Optional[str] = None, + **kw: Any, + ) -> None: + r"""Issue an "alter column" instruction using the + current migration context. + + Generally, only that aspect of the column which + is being changed, i.e. name, type, nullability, + default, needs to be specified. Multiple changes + can also be specified at once and the backend should + "do the right thing", emitting each change either + separately or together as the backend allows. + + MySQL has special requirements here, since MySQL + cannot ALTER a column without a full specification. + When producing MySQL-compatible migration files, + it is recommended that the ``existing_type``, + ``existing_server_default``, and ``existing_nullable`` + parameters be present, if not being altered. + + Type changes which are against the SQLAlchemy + "schema" types :class:`~sqlalchemy.types.Boolean` + and :class:`~sqlalchemy.types.Enum` may also + add or drop constraints which accompany those + types on backends that don't support them natively. + The ``existing_type`` argument is + used in this case to identify and remove a previous + constraint that was bound to the type object. + + :param table_name: string name of the target table. + :param column_name: string name of the target column, + as it exists before the operation begins. + :param nullable: Optional; specify ``True`` or ``False`` + to alter the column's nullability. + :param server_default: Optional; specify a string + SQL expression, :func:`~sqlalchemy.sql.expression.text`, + or :class:`~sqlalchemy.schema.DefaultClause` to indicate + an alteration to the column's default value. + Set to ``None`` to have the default removed. + :param comment: optional string text of a new comment to add to the + column. + :param new_column_name: Optional; specify a string name here to + indicate the new name within a column rename operation. + :param type\_: Optional; a :class:`~sqlalchemy.types.TypeEngine` + type object to specify a change to the column's type. + For SQLAlchemy types that also indicate a constraint (i.e. + :class:`~sqlalchemy.types.Boolean`, :class:`~sqlalchemy.types.Enum`), + the constraint is also generated. + :param autoincrement: set the ``AUTO_INCREMENT`` flag of the column; + currently understood by the MySQL dialect. + :param existing_type: Optional; a + :class:`~sqlalchemy.types.TypeEngine` + type object to specify the previous type. This + is required for all MySQL column alter operations that + don't otherwise specify a new type, as well as for + when nullability is being changed on a SQL Server + column. It is also used if the type is a so-called + SQLAlchemy "schema" type which may define a constraint (i.e. + :class:`~sqlalchemy.types.Boolean`, + :class:`~sqlalchemy.types.Enum`), + so that the constraint can be dropped. + :param existing_server_default: Optional; The existing + default value of the column. Required on MySQL if + an existing default is not being changed; else MySQL + removes the default. + :param existing_nullable: Optional; the existing nullability + of the column. Required on MySQL if the existing nullability + is not being changed; else MySQL sets this to NULL. + :param existing_autoincrement: Optional; the existing autoincrement + of the column. Used for MySQL's system of altering a column + that specifies ``AUTO_INCREMENT``. + :param existing_comment: string text of the existing comment on the + column to be maintained. Required on MySQL if the existing comment + on the column is not being changed. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + :param postgresql_using: String argument which will indicate a + SQL expression to render within the Postgresql-specific USING clause + within ALTER COLUMN. This string is taken directly as raw SQL which + must explicitly include any necessary quoting or escaping of tokens + within the expression. + + """ # noqa: E501 + ... + + def bulk_insert( + self, + table: Union[Table, TableClause], + rows: List[Dict[str, Any]], + *, + multiinsert: bool = True, + ) -> None: + """Issue a "bulk insert" operation using the current + migration context. + + This provides a means of representing an INSERT of multiple rows + which works equally well in the context of executing on a live + connection as well as that of generating a SQL script. In the + case of a SQL script, the values are rendered inline into the + statement. + + e.g.:: + + from alembic import op + from datetime import date + from sqlalchemy.sql import table, column + from sqlalchemy import String, Integer, Date + + # Create an ad-hoc table to use for the insert statement. + accounts_table = table( + "account", + column("id", Integer), + column("name", String), + column("create_date", Date), + ) + + op.bulk_insert( + accounts_table, + [ + { + "id": 1, + "name": "John Smith", + "create_date": date(2010, 10, 5), + }, + { + "id": 2, + "name": "Ed Williams", + "create_date": date(2007, 5, 27), + }, + { + "id": 3, + "name": "Wendy Jones", + "create_date": date(2008, 8, 15), + }, + ], + ) + + When using --sql mode, some datatypes may not render inline + automatically, such as dates and other special types. When this + issue is present, :meth:`.Operations.inline_literal` may be used:: + + op.bulk_insert( + accounts_table, + [ + { + "id": 1, + "name": "John Smith", + "create_date": op.inline_literal("2010-10-05"), + }, + { + "id": 2, + "name": "Ed Williams", + "create_date": op.inline_literal("2007-05-27"), + }, + { + "id": 3, + "name": "Wendy Jones", + "create_date": op.inline_literal("2008-08-15"), + }, + ], + multiinsert=False, + ) + + When using :meth:`.Operations.inline_literal` in conjunction with + :meth:`.Operations.bulk_insert`, in order for the statement to work + in "online" (e.g. non --sql) mode, the + :paramref:`~.Operations.bulk_insert.multiinsert` + flag should be set to ``False``, which will have the effect of + individual INSERT statements being emitted to the database, each + with a distinct VALUES clause, so that the "inline" values can + still be rendered, rather than attempting to pass the values + as bound parameters. + + :param table: a table object which represents the target of the INSERT. + + :param rows: a list of dictionaries indicating rows. + + :param multiinsert: when at its default of True and --sql mode is not + enabled, the INSERT statement will be executed using + "executemany()" style, where all elements in the list of + dictionaries are passed as bound parameters in a single + list. Setting this to False results in individual INSERT + statements being emitted per parameter set, and is needed + in those cases where non-literal values are present in the + parameter sets. + + """ # noqa: E501 + ... + + def create_check_constraint( + self, + constraint_name: Optional[str], + table_name: str, + condition: Union[str, ColumnElement[bool], TextClause], + *, + schema: Optional[str] = None, + **kw: Any, + ) -> None: + """Issue a "create check constraint" instruction using the + current migration context. + + e.g.:: + + from alembic import op + from sqlalchemy.sql import column, func + + op.create_check_constraint( + "ck_user_name_len", + "user", + func.len(column("name")) > 5, + ) + + CHECK constraints are usually against a SQL expression, so ad-hoc + table metadata is usually needed. The function will convert the given + arguments into a :class:`sqlalchemy.schema.CheckConstraint` bound + to an anonymous table in order to emit the CREATE statement. + + :param name: Name of the check constraint. The name is necessary + so that an ALTER statement can be emitted. For setups that + use an automated naming scheme such as that described at + :ref:`sqla:constraint_naming_conventions`, + ``name`` here can be ``None``, as the event listener will + apply the name to the constraint object when it is associated + with the table. + :param table_name: String name of the source table. + :param condition: SQL expression that's the condition of the + constraint. Can be a string or SQLAlchemy expression language + structure. + :param deferrable: optional bool. If set, emit DEFERRABLE or + NOT DEFERRABLE when issuing DDL for this constraint. + :param initially: optional string. If set, emit INITIALLY + when issuing DDL for this constraint. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ # noqa: E501 + ... + + def create_exclude_constraint( + self, + constraint_name: str, + table_name: str, + *elements: Any, + **kw: Any, + ) -> Optional[Table]: + """Issue an alter to create an EXCLUDE constraint using the + current migration context. + + .. note:: This method is Postgresql specific, and additionally + requires at least SQLAlchemy 1.0. + + e.g.:: + + from alembic import op + + op.create_exclude_constraint( + "user_excl", + "user", + ("period", "&&"), + ("group", "="), + where=("group != 'some group'"), + ) + + Note that the expressions work the same way as that of + the ``ExcludeConstraint`` object itself; if plain strings are + passed, quoting rules must be applied manually. + + :param name: Name of the constraint. + :param table_name: String name of the source table. + :param elements: exclude conditions. + :param where: SQL expression or SQL string with optional WHERE + clause. + :param deferrable: optional bool. If set, emit DEFERRABLE or + NOT DEFERRABLE when issuing DDL for this constraint. + :param initially: optional string. If set, emit INITIALLY + when issuing DDL for this constraint. + :param schema: Optional schema name to operate within. + + """ # noqa: E501 + ... + + def create_foreign_key( + self, + constraint_name: Optional[str], + source_table: str, + referent_table: str, + local_cols: List[str], + remote_cols: List[str], + *, + onupdate: Optional[str] = None, + ondelete: Optional[str] = None, + deferrable: Optional[bool] = None, + initially: Optional[str] = None, + match: Optional[str] = None, + source_schema: Optional[str] = None, + referent_schema: Optional[str] = None, + **dialect_kw: Any, + ) -> None: + """Issue a "create foreign key" instruction using the + current migration context. + + e.g.:: + + from alembic import op + + op.create_foreign_key( + "fk_user_address", + "address", + "user", + ["user_id"], + ["id"], + ) + + This internally generates a :class:`~sqlalchemy.schema.Table` object + containing the necessary columns, then generates a new + :class:`~sqlalchemy.schema.ForeignKeyConstraint` + object which it then associates with the + :class:`~sqlalchemy.schema.Table`. + Any event listeners associated with this action will be fired + off normally. The :class:`~sqlalchemy.schema.AddConstraint` + construct is ultimately used to generate the ALTER statement. + + :param constraint_name: Name of the foreign key constraint. The name + is necessary so that an ALTER statement can be emitted. For setups + that use an automated naming scheme such as that described at + :ref:`sqla:constraint_naming_conventions`, + ``name`` here can be ``None``, as the event listener will + apply the name to the constraint object when it is associated + with the table. + :param source_table: String name of the source table. + :param referent_table: String name of the destination table. + :param local_cols: a list of string column names in the + source table. + :param remote_cols: a list of string column names in the + remote table. + :param onupdate: Optional string. If set, emit ON UPDATE when + issuing DDL for this constraint. Typical values include CASCADE, + DELETE and RESTRICT. + :param ondelete: Optional string. If set, emit ON DELETE when + issuing DDL for this constraint. Typical values include CASCADE, + DELETE and RESTRICT. + :param deferrable: optional bool. If set, emit DEFERRABLE or NOT + DEFERRABLE when issuing DDL for this constraint. + :param source_schema: Optional schema name of the source table. + :param referent_schema: Optional schema name of the destination table. + + """ # noqa: E501 + ... + + def create_index( + self, + index_name: Optional[str], + table_name: str, + columns: Sequence[Union[str, TextClause, Function[Any]]], + *, + schema: Optional[str] = None, + unique: bool = False, + if_not_exists: Optional[bool] = None, + **kw: Any, + ) -> None: + r"""Issue a "create index" instruction using the current + migration context. + + e.g.:: + + from alembic import op + + op.create_index("ik_test", "t1", ["foo", "bar"]) + + Functional indexes can be produced by using the + :func:`sqlalchemy.sql.expression.text` construct:: + + from alembic import op + from sqlalchemy import text + + op.create_index("ik_test", "t1", [text("lower(foo)")]) + + :param index_name: name of the index. + :param table_name: name of the owning table. + :param columns: a list consisting of string column names and/or + :func:`~sqlalchemy.sql.expression.text` constructs. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + :param unique: If True, create a unique index. + + :param quote: Force quoting of this column's name on or off, + corresponding to ``True`` or ``False``. When left at its default + of ``None``, the column identifier will be quoted according to + whether the name is case sensitive (identifiers with at least one + upper case character are treated as case sensitive), or if it's a + reserved word. This flag is only needed to force quoting of a + reserved word which is not known by the SQLAlchemy dialect. + + :param if_not_exists: If True, adds IF NOT EXISTS operator when + creating the new index. + + .. versionadded:: 1.12.0 + + :param \**kw: Additional keyword arguments not mentioned above are + dialect specific, and passed in the form + ``_``. + See the documentation regarding an individual dialect at + :ref:`dialect_toplevel` for detail on documented arguments. + + """ # noqa: E501 + ... + + def create_primary_key( + self, + constraint_name: Optional[str], + table_name: str, + columns: List[str], + *, + schema: Optional[str] = None, + ) -> None: + """Issue a "create primary key" instruction using the current + migration context. + + e.g.:: + + from alembic import op + + op.create_primary_key("pk_my_table", "my_table", ["id", "version"]) + + This internally generates a :class:`~sqlalchemy.schema.Table` object + containing the necessary columns, then generates a new + :class:`~sqlalchemy.schema.PrimaryKeyConstraint` + object which it then associates with the + :class:`~sqlalchemy.schema.Table`. + Any event listeners associated with this action will be fired + off normally. The :class:`~sqlalchemy.schema.AddConstraint` + construct is ultimately used to generate the ALTER statement. + + :param constraint_name: Name of the primary key constraint. The name + is necessary so that an ALTER statement can be emitted. For setups + that use an automated naming scheme such as that described at + :ref:`sqla:constraint_naming_conventions` + ``name`` here can be ``None``, as the event listener will + apply the name to the constraint object when it is associated + with the table. + :param table_name: String name of the target table. + :param columns: a list of string column names to be applied to the + primary key constraint. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ # noqa: E501 + ... + + def create_table( + self, table_name: str, *columns: SchemaItem, **kw: Any + ) -> Table: + r"""Issue a "create table" instruction using the current migration + context. + + This directive receives an argument list similar to that of the + traditional :class:`sqlalchemy.schema.Table` construct, but without the + metadata:: + + from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column + from alembic import op + + op.create_table( + "account", + Column("id", INTEGER, primary_key=True), + Column("name", VARCHAR(50), nullable=False), + Column("description", NVARCHAR(200)), + Column("timestamp", TIMESTAMP, server_default=func.now()), + ) + + Note that :meth:`.create_table` accepts + :class:`~sqlalchemy.schema.Column` + constructs directly from the SQLAlchemy library. In particular, + default values to be created on the database side are + specified using the ``server_default`` parameter, and not + ``default`` which only specifies Python-side defaults:: + + from alembic import op + from sqlalchemy import Column, TIMESTAMP, func + + # specify "DEFAULT NOW" along with the "timestamp" column + op.create_table( + "account", + Column("id", INTEGER, primary_key=True), + Column("timestamp", TIMESTAMP, server_default=func.now()), + ) + + The function also returns a newly created + :class:`~sqlalchemy.schema.Table` object, corresponding to the table + specification given, which is suitable for + immediate SQL operations, in particular + :meth:`.Operations.bulk_insert`:: + + from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column + from alembic import op + + account_table = op.create_table( + "account", + Column("id", INTEGER, primary_key=True), + Column("name", VARCHAR(50), nullable=False), + Column("description", NVARCHAR(200)), + Column("timestamp", TIMESTAMP, server_default=func.now()), + ) + + op.bulk_insert( + account_table, + [ + {"name": "A1", "description": "account 1"}, + {"name": "A2", "description": "account 2"}, + ], + ) + + :param table_name: Name of the table + :param \*columns: collection of :class:`~sqlalchemy.schema.Column` + objects within + the table, as well as optional :class:`~sqlalchemy.schema.Constraint` + objects + and :class:`~.sqlalchemy.schema.Index` objects. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + :param \**kw: Other keyword arguments are passed to the underlying + :class:`sqlalchemy.schema.Table` object created for the command. + + :return: the :class:`~sqlalchemy.schema.Table` object corresponding + to the parameters given. + + """ # noqa: E501 + ... + + def create_table_comment( + self, + table_name: str, + comment: Optional[str], + *, + existing_comment: Optional[str] = None, + schema: Optional[str] = None, + ) -> None: + """Emit a COMMENT ON operation to set the comment for a table. + + :param table_name: string name of the target table. + :param comment: string value of the comment being registered against + the specified table. + :param existing_comment: String value of a comment + already registered on the specified table, used within autogenerate + so that the operation is reversible, but not required for direct + use. + + .. seealso:: + + :meth:`.Operations.drop_table_comment` + + :paramref:`.Operations.alter_column.comment` + + """ # noqa: E501 + ... + + def create_unique_constraint( + self, + constraint_name: Optional[str], + table_name: str, + columns: Sequence[str], + *, + schema: Optional[str] = None, + **kw: Any, + ) -> Any: + """Issue a "create unique constraint" instruction using the + current migration context. + + e.g.:: + + from alembic import op + op.create_unique_constraint("uq_user_name", "user", ["name"]) + + This internally generates a :class:`~sqlalchemy.schema.Table` object + containing the necessary columns, then generates a new + :class:`~sqlalchemy.schema.UniqueConstraint` + object which it then associates with the + :class:`~sqlalchemy.schema.Table`. + Any event listeners associated with this action will be fired + off normally. The :class:`~sqlalchemy.schema.AddConstraint` + construct is ultimately used to generate the ALTER statement. + + :param name: Name of the unique constraint. The name is necessary + so that an ALTER statement can be emitted. For setups that + use an automated naming scheme such as that described at + :ref:`sqla:constraint_naming_conventions`, + ``name`` here can be ``None``, as the event listener will + apply the name to the constraint object when it is associated + with the table. + :param table_name: String name of the source table. + :param columns: a list of string column names in the + source table. + :param deferrable: optional bool. If set, emit DEFERRABLE or + NOT DEFERRABLE when issuing DDL for this constraint. + :param initially: optional string. If set, emit INITIALLY + when issuing DDL for this constraint. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ # noqa: E501 + ... + + def drop_column( + self, + table_name: str, + column_name: str, + *, + schema: Optional[str] = None, + **kw: Any, + ) -> None: + """Issue a "drop column" instruction using the current + migration context. + + e.g.:: + + drop_column("organization", "account_id") + + :param table_name: name of table + :param column_name: name of column + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + :param mssql_drop_check: Optional boolean. When ``True``, on + Microsoft SQL Server only, first + drop the CHECK constraint on the column using a + SQL-script-compatible + block that selects into a @variable from sys.check_constraints, + then exec's a separate DROP CONSTRAINT for that constraint. + :param mssql_drop_default: Optional boolean. When ``True``, on + Microsoft SQL Server only, first + drop the DEFAULT constraint on the column using a + SQL-script-compatible + block that selects into a @variable from sys.default_constraints, + then exec's a separate DROP CONSTRAINT for that default. + :param mssql_drop_foreign_key: Optional boolean. When ``True``, on + Microsoft SQL Server only, first + drop a single FOREIGN KEY constraint on the column using a + SQL-script-compatible + block that selects into a @variable from + sys.foreign_keys/sys.foreign_key_columns, + then exec's a separate DROP CONSTRAINT for that default. Only + works if the column has exactly one FK constraint which refers to + it, at the moment. + + """ # noqa: E501 + ... + + def drop_constraint( + self, + constraint_name: str, + table_name: str, + type_: Optional[str] = None, + *, + schema: Optional[str] = None, + ) -> None: + r"""Drop a constraint of the given name, typically via DROP CONSTRAINT. + + :param constraint_name: name of the constraint. + :param table_name: table name. + :param type\_: optional, required on MySQL. can be + 'foreignkey', 'primary', 'unique', or 'check'. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ # noqa: E501 + ... + + def drop_index( + self, + index_name: str, + table_name: Optional[str] = None, + *, + schema: Optional[str] = None, + if_exists: Optional[bool] = None, + **kw: Any, + ) -> None: + r"""Issue a "drop index" instruction using the current + migration context. + + e.g.:: + + drop_index("accounts") + + :param index_name: name of the index. + :param table_name: name of the owning table. Some + backends such as Microsoft SQL Server require this. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + :param if_exists: If True, adds IF EXISTS operator when + dropping the index. + + .. versionadded:: 1.12.0 + + :param \**kw: Additional keyword arguments not mentioned above are + dialect specific, and passed in the form + ``_``. + See the documentation regarding an individual dialect at + :ref:`dialect_toplevel` for detail on documented arguments. + + """ # noqa: E501 + ... + + def drop_table( + self, table_name: str, *, schema: Optional[str] = None, **kw: Any + ) -> None: + r"""Issue a "drop table" instruction using the current + migration context. + + + e.g.:: + + drop_table("accounts") + + :param table_name: Name of the table + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + :param \**kw: Other keyword arguments are passed to the underlying + :class:`sqlalchemy.schema.Table` object created for the command. + + """ # noqa: E501 + ... + + def drop_table_comment( + self, + table_name: str, + *, + existing_comment: Optional[str] = None, + schema: Optional[str] = None, + ) -> None: + """Issue a "drop table comment" operation to + remove an existing comment set on a table. + + :param table_name: string name of the target table. + :param existing_comment: An optional string value of a comment already + registered on the specified table. + + .. seealso:: + + :meth:`.Operations.create_table_comment` + + :paramref:`.Operations.alter_column.comment` + + """ # noqa: E501 + ... + + def execute( + self, + sqltext: Union[Executable, str], + *, + execution_options: Optional[dict[str, Any]] = None, + ) -> None: + r"""Execute the given SQL using the current migration context. + + The given SQL can be a plain string, e.g.:: + + op.execute("INSERT INTO table (foo) VALUES ('some value')") + + Or it can be any kind of Core SQL Expression construct, such as + below where we use an update construct:: + + from sqlalchemy.sql import table, column + from sqlalchemy import String + from alembic import op + + account = table("account", column("name", String)) + op.execute( + account.update() + .where(account.c.name == op.inline_literal("account 1")) + .values({"name": op.inline_literal("account 2")}) + ) + + Above, we made use of the SQLAlchemy + :func:`sqlalchemy.sql.expression.table` and + :func:`sqlalchemy.sql.expression.column` constructs to make a brief, + ad-hoc table construct just for our UPDATE statement. A full + :class:`~sqlalchemy.schema.Table` construct of course works perfectly + fine as well, though note it's a recommended practice to at least + ensure the definition of a table is self-contained within the migration + script, rather than imported from a module that may break compatibility + with older migrations. + + In a SQL script context, the statement is emitted directly to the + output stream. There is *no* return result, however, as this + function is oriented towards generating a change script + that can run in "offline" mode. Additionally, parameterized + statements are discouraged here, as they *will not work* in offline + mode. Above, we use :meth:`.inline_literal` where parameters are + to be used. + + For full interaction with a connected database where parameters can + also be used normally, use the "bind" available from the context:: + + from alembic import op + + connection = op.get_bind() + + connection.execute( + account.update() + .where(account.c.name == "account 1") + .values({"name": "account 2"}) + ) + + Additionally, when passing the statement as a plain string, it is first + coerced into a :func:`sqlalchemy.sql.expression.text` construct + before being passed along. In the less likely case that the + literal SQL string contains a colon, it must be escaped with a + backslash, as:: + + op.execute(r"INSERT INTO table (foo) VALUES ('\:colon_value')") + + + :param sqltext: Any legal SQLAlchemy expression, including: + + * a string + * a :func:`sqlalchemy.sql.expression.text` construct. + * a :func:`sqlalchemy.sql.expression.insert` construct. + * a :func:`sqlalchemy.sql.expression.update` construct. + * a :func:`sqlalchemy.sql.expression.delete` construct. + * Any "executable" described in SQLAlchemy Core documentation, + noting that no result set is returned. + + .. note:: when passing a plain string, the statement is coerced into + a :func:`sqlalchemy.sql.expression.text` construct. This construct + considers symbols with colons, e.g. ``:foo`` to be bound parameters. + To avoid this, ensure that colon symbols are escaped, e.g. + ``\:foo``. + + :param execution_options: Optional dictionary of + execution options, will be passed to + :meth:`sqlalchemy.engine.Connection.execution_options`. + """ # noqa: E501 + ... + + def rename_table( + self, + old_table_name: str, + new_table_name: str, + *, + schema: Optional[str] = None, + ) -> None: + """Emit an ALTER TABLE to rename a table. + + :param old_table_name: old name. + :param new_table_name: new name. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ # noqa: E501 + ... + + # END STUB FUNCTIONS: op_cls + + +class BatchOperations(AbstractOperations): + """Modifies the interface :class:`.Operations` for batch mode. + + This basically omits the ``table_name`` and ``schema`` parameters + from associated methods, as these are a given when running under batch + mode. + + .. seealso:: + + :meth:`.Operations.batch_alter_table` + + Note that as of 0.8, most of the methods on this class are produced + dynamically using the :meth:`.Operations.register_operation` + method. + + """ + + impl: BatchOperationsImpl + + def _noop(self, operation: Any) -> NoReturn: + raise NotImplementedError( + "The %s method does not apply to a batch table alter operation." + % operation + ) + + if TYPE_CHECKING: + # START STUB FUNCTIONS: batch_op + # ### the following stubs are generated by tools/write_pyi.py ### + # ### do not edit ### + + def add_column( + self, + column: Column[Any], + *, + insert_before: Optional[str] = None, + insert_after: Optional[str] = None, + ) -> None: + """Issue an "add column" instruction using the current + batch migration context. + + .. seealso:: + + :meth:`.Operations.add_column` + + """ # noqa: E501 + ... + + def alter_column( + self, + column_name: str, + *, + nullable: Optional[bool] = None, + comment: Union[str, Literal[False], None] = False, + server_default: Any = False, + new_column_name: Optional[str] = None, + type_: Union[TypeEngine[Any], Type[TypeEngine[Any]], None] = None, + existing_type: Union[ + TypeEngine[Any], Type[TypeEngine[Any]], None + ] = None, + existing_server_default: Union[ + str, bool, Identity, Computed, None + ] = False, + existing_nullable: Optional[bool] = None, + existing_comment: Optional[str] = None, + insert_before: Optional[str] = None, + insert_after: Optional[str] = None, + **kw: Any, + ) -> None: + """Issue an "alter column" instruction using the current + batch migration context. + + Parameters are the same as that of :meth:`.Operations.alter_column`, + as well as the following option(s): + + :param insert_before: String name of an existing column which this + column should be placed before, when creating the new table. + + :param insert_after: String name of an existing column which this + column should be placed after, when creating the new table. If + both :paramref:`.BatchOperations.alter_column.insert_before` + and :paramref:`.BatchOperations.alter_column.insert_after` are + omitted, the column is inserted after the last existing column + in the table. + + .. seealso:: + + :meth:`.Operations.alter_column` + + + """ # noqa: E501 + ... + + def create_check_constraint( + self, + constraint_name: str, + condition: Union[str, ColumnElement[bool], TextClause], + **kw: Any, + ) -> None: + """Issue a "create check constraint" instruction using the + current batch migration context. + + The batch form of this call omits the ``source`` and ``schema`` + arguments from the call. + + .. seealso:: + + :meth:`.Operations.create_check_constraint` + + """ # noqa: E501 + ... + + def create_exclude_constraint( + self, constraint_name: str, *elements: Any, **kw: Any + ) -> Optional[Table]: + """Issue a "create exclude constraint" instruction using the + current batch migration context. + + .. note:: This method is Postgresql specific, and additionally + requires at least SQLAlchemy 1.0. + + .. seealso:: + + :meth:`.Operations.create_exclude_constraint` + + """ # noqa: E501 + ... + + def create_foreign_key( + self, + constraint_name: str, + referent_table: str, + local_cols: List[str], + remote_cols: List[str], + *, + referent_schema: Optional[str] = None, + onupdate: Optional[str] = None, + ondelete: Optional[str] = None, + deferrable: Optional[bool] = None, + initially: Optional[str] = None, + match: Optional[str] = None, + **dialect_kw: Any, + ) -> None: + """Issue a "create foreign key" instruction using the + current batch migration context. + + The batch form of this call omits the ``source`` and ``source_schema`` + arguments from the call. + + e.g.:: + + with batch_alter_table("address") as batch_op: + batch_op.create_foreign_key( + "fk_user_address", + "user", + ["user_id"], + ["id"], + ) + + .. seealso:: + + :meth:`.Operations.create_foreign_key` + + """ # noqa: E501 + ... + + def create_index( + self, index_name: str, columns: List[str], **kw: Any + ) -> None: + """Issue a "create index" instruction using the + current batch migration context. + + .. seealso:: + + :meth:`.Operations.create_index` + + """ # noqa: E501 + ... + + def create_primary_key( + self, constraint_name: str, columns: List[str] + ) -> None: + """Issue a "create primary key" instruction using the + current batch migration context. + + The batch form of this call omits the ``table_name`` and ``schema`` + arguments from the call. + + .. seealso:: + + :meth:`.Operations.create_primary_key` + + """ # noqa: E501 + ... + + def create_table_comment( + self, + comment: Optional[str], + *, + existing_comment: Optional[str] = None, + ) -> None: + """Emit a COMMENT ON operation to set the comment for a table + using the current batch migration context. + + :param comment: string value of the comment being registered against + the specified table. + :param existing_comment: String value of a comment + already registered on the specified table, used within autogenerate + so that the operation is reversible, but not required for direct + use. + + """ # noqa: E501 + ... + + def create_unique_constraint( + self, constraint_name: str, columns: Sequence[str], **kw: Any + ) -> Any: + """Issue a "create unique constraint" instruction using the + current batch migration context. + + The batch form of this call omits the ``source`` and ``schema`` + arguments from the call. + + .. seealso:: + + :meth:`.Operations.create_unique_constraint` + + """ # noqa: E501 + ... + + def drop_column(self, column_name: str, **kw: Any) -> None: + """Issue a "drop column" instruction using the current + batch migration context. + + .. seealso:: + + :meth:`.Operations.drop_column` + + """ # noqa: E501 + ... + + def drop_constraint( + self, constraint_name: str, type_: Optional[str] = None + ) -> None: + """Issue a "drop constraint" instruction using the + current batch migration context. + + The batch form of this call omits the ``table_name`` and ``schema`` + arguments from the call. + + .. seealso:: + + :meth:`.Operations.drop_constraint` + + """ # noqa: E501 + ... + + def drop_index(self, index_name: str, **kw: Any) -> None: + """Issue a "drop index" instruction using the + current batch migration context. + + .. seealso:: + + :meth:`.Operations.drop_index` + + """ # noqa: E501 + ... + + def drop_table_comment( + self, *, existing_comment: Optional[str] = None + ) -> None: + """Issue a "drop table comment" operation to + remove an existing comment set on a table using the current + batch operations context. + + :param existing_comment: An optional string value of a comment already + registered on the specified table. + + """ # noqa: E501 + ... + + def execute( + self, + sqltext: Union[Executable, str], + *, + execution_options: Optional[dict[str, Any]] = None, + ) -> None: + """Execute the given SQL using the current migration context. + + .. seealso:: + + :meth:`.Operations.execute` + + """ # noqa: E501 + ... + + # END STUB FUNCTIONS: batch_op diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/batch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/batch.py new file mode 100644 index 0000000000000000000000000000000000000000..fd7ab990306aff0501b39ea96fde31b81d20ff94 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/batch.py @@ -0,0 +1,717 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +from typing import Any +from typing import Dict +from typing import List +from typing import Optional +from typing import Tuple +from typing import TYPE_CHECKING +from typing import Union + +from sqlalchemy import CheckConstraint +from sqlalchemy import Column +from sqlalchemy import ForeignKeyConstraint +from sqlalchemy import Index +from sqlalchemy import MetaData +from sqlalchemy import PrimaryKeyConstraint +from sqlalchemy import schema as sql_schema +from sqlalchemy import Table +from sqlalchemy import types as sqltypes +from sqlalchemy.sql.schema import SchemaEventTarget +from sqlalchemy.util import OrderedDict +from sqlalchemy.util import topological + +from ..util import exc +from ..util.sqla_compat import _columns_for_constraint +from ..util.sqla_compat import _copy +from ..util.sqla_compat import _copy_expression +from ..util.sqla_compat import _ensure_scope_for_ddl +from ..util.sqla_compat import _fk_is_self_referential +from ..util.sqla_compat import _idx_table_bound_expressions +from ..util.sqla_compat import _insert_inline +from ..util.sqla_compat import _is_type_bound +from ..util.sqla_compat import _remove_column_from_collection +from ..util.sqla_compat import _resolve_for_variant +from ..util.sqla_compat import _select +from ..util.sqla_compat import constraint_name_defined +from ..util.sqla_compat import constraint_name_string + +if TYPE_CHECKING: + from typing import Literal + + from sqlalchemy.engine import Dialect + from sqlalchemy.sql.elements import ColumnClause + from sqlalchemy.sql.elements import quoted_name + from sqlalchemy.sql.functions import Function + from sqlalchemy.sql.schema import Constraint + from sqlalchemy.sql.type_api import TypeEngine + + from ..ddl.impl import DefaultImpl + + +class BatchOperationsImpl: + def __init__( + self, + operations, + table_name, + schema, + recreate, + copy_from, + table_args, + table_kwargs, + reflect_args, + reflect_kwargs, + naming_convention, + partial_reordering, + ): + self.operations = operations + self.table_name = table_name + self.schema = schema + if recreate not in ("auto", "always", "never"): + raise ValueError( + "recreate may be one of 'auto', 'always', or 'never'." + ) + self.recreate = recreate + self.copy_from = copy_from + self.table_args = table_args + self.table_kwargs = dict(table_kwargs) + self.reflect_args = reflect_args + self.reflect_kwargs = dict(reflect_kwargs) + self.reflect_kwargs.setdefault( + "listeners", list(self.reflect_kwargs.get("listeners", ())) + ) + self.reflect_kwargs["listeners"].append( + ("column_reflect", operations.impl.autogen_column_reflect) + ) + self.naming_convention = naming_convention + self.partial_reordering = partial_reordering + self.batch = [] + + @property + def dialect(self) -> Dialect: + return self.operations.impl.dialect + + @property + def impl(self) -> DefaultImpl: + return self.operations.impl + + def _should_recreate(self) -> bool: + if self.recreate == "auto": + return self.operations.impl.requires_recreate_in_batch(self) + elif self.recreate == "always": + return True + else: + return False + + def flush(self) -> None: + should_recreate = self._should_recreate() + + with _ensure_scope_for_ddl(self.impl.connection): + if not should_recreate: + for opname, arg, kw in self.batch: + fn = getattr(self.operations.impl, opname) + fn(*arg, **kw) + else: + if self.naming_convention: + m1 = MetaData(naming_convention=self.naming_convention) + else: + m1 = MetaData() + + if self.copy_from is not None: + existing_table = self.copy_from + reflected = False + else: + if self.operations.migration_context.as_sql: + raise exc.CommandError( + f"This operation cannot proceed in --sql mode; " + f"batch mode with dialect " + f"{self.operations.migration_context.dialect.name} " # noqa: E501 + f"requires a live database connection with which " + f'to reflect the table "{self.table_name}". ' + f"To generate a batch SQL migration script using " + "table " + '"move and copy", a complete Table object ' + f'should be passed to the "copy_from" argument ' + "of the batch_alter_table() method so that table " + "reflection can be skipped." + ) + + existing_table = Table( + self.table_name, + m1, + schema=self.schema, + autoload_with=self.operations.get_bind(), + *self.reflect_args, + **self.reflect_kwargs, + ) + reflected = True + + batch_impl = ApplyBatchImpl( + self.impl, + existing_table, + self.table_args, + self.table_kwargs, + reflected, + partial_reordering=self.partial_reordering, + ) + for opname, arg, kw in self.batch: + fn = getattr(batch_impl, opname) + fn(*arg, **kw) + + batch_impl._create(self.impl) + + def alter_column(self, *arg, **kw) -> None: + self.batch.append(("alter_column", arg, kw)) + + def add_column(self, *arg, **kw) -> None: + if ( + "insert_before" in kw or "insert_after" in kw + ) and not self._should_recreate(): + raise exc.CommandError( + "Can't specify insert_before or insert_after when using " + "ALTER; please specify recreate='always'" + ) + self.batch.append(("add_column", arg, kw)) + + def drop_column(self, *arg, **kw) -> None: + self.batch.append(("drop_column", arg, kw)) + + def add_constraint(self, const: Constraint) -> None: + self.batch.append(("add_constraint", (const,), {})) + + def drop_constraint(self, const: Constraint) -> None: + self.batch.append(("drop_constraint", (const,), {})) + + def rename_table(self, *arg, **kw): + self.batch.append(("rename_table", arg, kw)) + + def create_index(self, idx: Index, **kw: Any) -> None: + self.batch.append(("create_index", (idx,), kw)) + + def drop_index(self, idx: Index, **kw: Any) -> None: + self.batch.append(("drop_index", (idx,), kw)) + + def create_table_comment(self, table): + self.batch.append(("create_table_comment", (table,), {})) + + def drop_table_comment(self, table): + self.batch.append(("drop_table_comment", (table,), {})) + + def create_table(self, table): + raise NotImplementedError("Can't create table in batch mode") + + def drop_table(self, table): + raise NotImplementedError("Can't drop table in batch mode") + + def create_column_comment(self, column): + self.batch.append(("create_column_comment", (column,), {})) + + +class ApplyBatchImpl: + def __init__( + self, + impl: DefaultImpl, + table: Table, + table_args: tuple, + table_kwargs: Dict[str, Any], + reflected: bool, + partial_reordering: tuple = (), + ) -> None: + self.impl = impl + self.table = table # this is a Table object + self.table_args = table_args + self.table_kwargs = table_kwargs + self.temp_table_name = self._calc_temp_name(table.name) + self.new_table: Optional[Table] = None + + self.partial_reordering = partial_reordering # tuple of tuples + self.add_col_ordering: Tuple[ + Tuple[str, str], ... + ] = () # tuple of tuples + + self.column_transfers = OrderedDict( + (c.name, {"expr": c}) for c in self.table.c + ) + self.existing_ordering = list(self.column_transfers) + + self.reflected = reflected + self._grab_table_elements() + + @classmethod + def _calc_temp_name(cls, tablename: Union[quoted_name, str]) -> str: + return ("_alembic_tmp_%s" % tablename)[0:50] + + def _grab_table_elements(self) -> None: + schema = self.table.schema + self.columns: Dict[str, Column[Any]] = OrderedDict() + for c in self.table.c: + c_copy = _copy(c, schema=schema) + c_copy.unique = c_copy.index = False + # ensure that the type object was copied, + # as we may need to modify it in-place + if isinstance(c.type, SchemaEventTarget): + assert c_copy.type is not c.type + self.columns[c.name] = c_copy + self.named_constraints: Dict[str, Constraint] = {} + self.unnamed_constraints = [] + self.col_named_constraints = {} + self.indexes: Dict[str, Index] = {} + self.new_indexes: Dict[str, Index] = {} + + for const in self.table.constraints: + if _is_type_bound(const): + continue + elif ( + self.reflected + and isinstance(const, CheckConstraint) + and not const.name + ): + # TODO: we are skipping unnamed reflected CheckConstraint + # because + # we have no way to determine _is_type_bound() for these. + pass + elif constraint_name_string(const.name): + self.named_constraints[const.name] = const + else: + self.unnamed_constraints.append(const) + + if not self.reflected: + for col in self.table.c: + for const in col.constraints: + if const.name: + self.col_named_constraints[const.name] = (col, const) + + for idx in self.table.indexes: + self.indexes[idx.name] = idx # type: ignore[index] + + for k in self.table.kwargs: + self.table_kwargs.setdefault(k, self.table.kwargs[k]) + + def _adjust_self_columns_for_partial_reordering(self) -> None: + pairs = set() + + col_by_idx = list(self.columns) + + if self.partial_reordering: + for tuple_ in self.partial_reordering: + for index, elem in enumerate(tuple_): + if index > 0: + pairs.add((tuple_[index - 1], elem)) + else: + for index, elem in enumerate(self.existing_ordering): + if index > 0: + pairs.add((col_by_idx[index - 1], elem)) + + pairs.update(self.add_col_ordering) + + # this can happen if some columns were dropped and not removed + # from existing_ordering. this should be prevented already, but + # conservatively making sure this didn't happen + pairs_list = [p for p in pairs if p[0] != p[1]] + + sorted_ = list( + topological.sort(pairs_list, col_by_idx, deterministic_order=True) + ) + self.columns = OrderedDict((k, self.columns[k]) for k in sorted_) + self.column_transfers = OrderedDict( + (k, self.column_transfers[k]) for k in sorted_ + ) + + def _transfer_elements_to_new_table(self) -> None: + assert self.new_table is None, "Can only create new table once" + + m = MetaData() + schema = self.table.schema + + if self.partial_reordering or self.add_col_ordering: + self._adjust_self_columns_for_partial_reordering() + + self.new_table = new_table = Table( + self.temp_table_name, + m, + *(list(self.columns.values()) + list(self.table_args)), + schema=schema, + **self.table_kwargs, + ) + + for const in ( + list(self.named_constraints.values()) + self.unnamed_constraints + ): + const_columns = {c.key for c in _columns_for_constraint(const)} + + if not const_columns.issubset(self.column_transfers): + continue + + const_copy: Constraint + if isinstance(const, ForeignKeyConstraint): + if _fk_is_self_referential(const): + # for self-referential constraint, refer to the + # *original* table name, and not _alembic_batch_temp. + # This is consistent with how we're handling + # FK constraints from other tables; we assume SQLite + # no foreign keys just keeps the names unchanged, so + # when we rename back, they match again. + const_copy = _copy( + const, schema=schema, target_table=self.table + ) + else: + # "target_table" for ForeignKeyConstraint.copy() is + # only used if the FK is detected as being + # self-referential, which we are handling above. + const_copy = _copy(const, schema=schema) + else: + const_copy = _copy( + const, schema=schema, target_table=new_table + ) + if isinstance(const, ForeignKeyConstraint): + self._setup_referent(m, const) + new_table.append_constraint(const_copy) + + def _gather_indexes_from_both_tables(self) -> List[Index]: + assert self.new_table is not None + idx: List[Index] = [] + + for idx_existing in self.indexes.values(): + # this is a lift-and-move from Table.to_metadata + + if idx_existing._column_flag: + continue + + idx_copy = Index( + idx_existing.name, + unique=idx_existing.unique, + *[ + _copy_expression(expr, self.new_table) + for expr in _idx_table_bound_expressions(idx_existing) + ], + _table=self.new_table, + **idx_existing.kwargs, + ) + idx.append(idx_copy) + + for index in self.new_indexes.values(): + idx.append( + Index( + index.name, + unique=index.unique, + *[self.new_table.c[col] for col in index.columns.keys()], + **index.kwargs, + ) + ) + return idx + + def _setup_referent( + self, metadata: MetaData, constraint: ForeignKeyConstraint + ) -> None: + spec = constraint.elements[0]._get_colspec() + parts = spec.split(".") + tname = parts[-2] + if len(parts) == 3: + referent_schema = parts[0] + else: + referent_schema = None + + if tname != self.temp_table_name: + key = sql_schema._get_table_key(tname, referent_schema) + + def colspec(elem: Any): + return elem._get_colspec() + + if key in metadata.tables: + t = metadata.tables[key] + for elem in constraint.elements: + colname = colspec(elem).split(".")[-1] + if colname not in t.c: + t.append_column(Column(colname, sqltypes.NULLTYPE)) + else: + Table( + tname, + metadata, + *[ + Column(n, sqltypes.NULLTYPE) + for n in [ + colspec(elem).split(".")[-1] + for elem in constraint.elements + ] + ], + schema=referent_schema, + ) + + def _create(self, op_impl: DefaultImpl) -> None: + self._transfer_elements_to_new_table() + + op_impl.prep_table_for_batch(self, self.table) + assert self.new_table is not None + op_impl.create_table(self.new_table) + + try: + op_impl._exec( + _insert_inline(self.new_table).from_select( + list( + k + for k, transfer in self.column_transfers.items() + if "expr" in transfer + ), + _select( + *[ + transfer["expr"] + for transfer in self.column_transfers.values() + if "expr" in transfer + ] + ), + ) + ) + op_impl.drop_table(self.table) + except: + op_impl.drop_table(self.new_table) + raise + else: + op_impl.rename_table( + self.temp_table_name, self.table.name, schema=self.table.schema + ) + self.new_table.name = self.table.name + try: + for idx in self._gather_indexes_from_both_tables(): + op_impl.create_index(idx) + finally: + self.new_table.name = self.temp_table_name + + def alter_column( + self, + table_name: str, + column_name: str, + nullable: Optional[bool] = None, + server_default: Optional[Union[Function[Any], str, bool]] = False, + name: Optional[str] = None, + type_: Optional[TypeEngine] = None, + autoincrement: Optional[Union[bool, Literal["auto"]]] = None, + comment: Union[str, Literal[False]] = False, + **kw, + ) -> None: + existing = self.columns[column_name] + existing_transfer: Dict[str, Any] = self.column_transfers[column_name] + if name is not None and name != column_name: + # note that we don't change '.key' - we keep referring + # to the renamed column by its old key in _create(). neat! + existing.name = name + existing_transfer["name"] = name + + existing_type = kw.get("existing_type", None) + if existing_type: + resolved_existing_type = _resolve_for_variant( + kw["existing_type"], self.impl.dialect + ) + + # pop named constraints for Boolean/Enum for rename + if ( + isinstance(resolved_existing_type, SchemaEventTarget) + and resolved_existing_type.name # type:ignore[attr-defined] # noqa E501 + ): + self.named_constraints.pop( + resolved_existing_type.name, # type:ignore[attr-defined] # noqa E501 + None, + ) + + if type_ is not None: + type_ = sqltypes.to_instance(type_) + # old type is being discarded so turn off eventing + # rules. Alternatively we can + # erase the events set up by this type, but this is simpler. + # we also ignore the drop_constraint that will come here from + # Operations.implementation_for(alter_column) + + if isinstance(existing.type, SchemaEventTarget): + existing.type._create_events = ( # type:ignore[attr-defined] + existing.type.create_constraint # type:ignore[attr-defined] # noqa + ) = False + + self.impl.cast_for_batch_migrate( + existing, existing_transfer, type_ + ) + + existing.type = type_ + + # we *dont* however set events for the new type, because + # alter_column is invoked from + # Operations.implementation_for(alter_column) which already + # will emit an add_constraint() + + if nullable is not None: + existing.nullable = nullable + if server_default is not False: + if server_default is None: + existing.server_default = None + else: + sql_schema.DefaultClause( + server_default # type: ignore[arg-type] + )._set_parent(existing) + if autoincrement is not None: + existing.autoincrement = bool(autoincrement) + + if comment is not False: + existing.comment = comment + + def _setup_dependencies_for_add_column( + self, + colname: str, + insert_before: Optional[str], + insert_after: Optional[str], + ) -> None: + index_cols = self.existing_ordering + col_indexes = {name: i for i, name in enumerate(index_cols)} + + if not self.partial_reordering: + if insert_after: + if not insert_before: + if insert_after in col_indexes: + # insert after an existing column + idx = col_indexes[insert_after] + 1 + if idx < len(index_cols): + insert_before = index_cols[idx] + else: + # insert after a column that is also new + insert_before = dict(self.add_col_ordering)[ + insert_after + ] + if insert_before: + if not insert_after: + if insert_before in col_indexes: + # insert before an existing column + idx = col_indexes[insert_before] - 1 + if idx >= 0: + insert_after = index_cols[idx] + else: + # insert before a column that is also new + insert_after = { + b: a for a, b in self.add_col_ordering + }[insert_before] + + if insert_before: + self.add_col_ordering += ((colname, insert_before),) + if insert_after: + self.add_col_ordering += ((insert_after, colname),) + + if ( + not self.partial_reordering + and not insert_before + and not insert_after + and col_indexes + ): + self.add_col_ordering += ((index_cols[-1], colname),) + + def add_column( + self, + table_name: str, + column: Column[Any], + insert_before: Optional[str] = None, + insert_after: Optional[str] = None, + **kw, + ) -> None: + self._setup_dependencies_for_add_column( + column.name, insert_before, insert_after + ) + # we copy the column because operations.add_column() + # gives us a Column that is part of a Table already. + self.columns[column.name] = _copy(column, schema=self.table.schema) + self.column_transfers[column.name] = {} + + def drop_column( + self, + table_name: str, + column: Union[ColumnClause[Any], Column[Any]], + **kw, + ) -> None: + if column.name in self.table.primary_key.columns: + _remove_column_from_collection( + self.table.primary_key.columns, column + ) + del self.columns[column.name] + del self.column_transfers[column.name] + self.existing_ordering.remove(column.name) + + # pop named constraints for Boolean/Enum for rename + if ( + "existing_type" in kw + and isinstance(kw["existing_type"], SchemaEventTarget) + and kw["existing_type"].name # type:ignore[attr-defined] + ): + self.named_constraints.pop( + kw["existing_type"].name, None # type:ignore[attr-defined] + ) + + def create_column_comment(self, column): + """the batch table creation function will issue create_column_comment + on the real "impl" as part of the create table process. + + That is, the Column object will have the comment on it already, + so when it is received by add_column() it will be a normal part of + the CREATE TABLE and doesn't need an extra step here. + + """ + + def create_table_comment(self, table): + """the batch table creation function will issue create_table_comment + on the real "impl" as part of the create table process. + + """ + + def drop_table_comment(self, table): + """the batch table creation function will issue drop_table_comment + on the real "impl" as part of the create table process. + + """ + + def add_constraint(self, const: Constraint) -> None: + if not constraint_name_defined(const.name): + raise ValueError("Constraint must have a name") + if isinstance(const, sql_schema.PrimaryKeyConstraint): + if self.table.primary_key in self.unnamed_constraints: + self.unnamed_constraints.remove(self.table.primary_key) + + if constraint_name_string(const.name): + self.named_constraints[const.name] = const + else: + self.unnamed_constraints.append(const) + + def drop_constraint(self, const: Constraint) -> None: + if not const.name: + raise ValueError("Constraint must have a name") + try: + if const.name in self.col_named_constraints: + col, const = self.col_named_constraints.pop(const.name) + + for col_const in list(self.columns[col.name].constraints): + if col_const.name == const.name: + self.columns[col.name].constraints.remove(col_const) + elif constraint_name_string(const.name): + const = self.named_constraints.pop(const.name) + elif const in self.unnamed_constraints: + self.unnamed_constraints.remove(const) + + except KeyError: + if _is_type_bound(const): + # type-bound constraints are only included in the new + # table via their type object in any case, so ignore the + # drop_constraint() that comes here via the + # Operations.implementation_for(alter_column) + return + raise ValueError("No such constraint: '%s'" % const.name) + else: + if isinstance(const, PrimaryKeyConstraint): + for col in const.columns: + self.columns[col.name].primary_key = False + + def create_index(self, idx: Index) -> None: + self.new_indexes[idx.name] = idx # type: ignore[index] + + def drop_index(self, idx: Index) -> None: + try: + del self.indexes[idx.name] # type: ignore[arg-type] + except KeyError: + raise ValueError("No such index: '%s'" % idx.name) + + def rename_table(self, *arg, **kw): + raise NotImplementedError("TODO") diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/ops.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..7b65191cf20fa5bc1be08c646247dee611f4f4fe --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/ops.py @@ -0,0 +1,2786 @@ +from __future__ import annotations + +from abc import abstractmethod +import re +from typing import Any +from typing import Callable +from typing import cast +from typing import Dict +from typing import FrozenSet +from typing import Iterator +from typing import List +from typing import MutableMapping +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from sqlalchemy.types import NULLTYPE + +from . import schemaobj +from .base import BatchOperations +from .base import Operations +from .. import util +from ..util import sqla_compat + +if TYPE_CHECKING: + from typing import Literal + + from sqlalchemy.sql import Executable + from sqlalchemy.sql.elements import ColumnElement + from sqlalchemy.sql.elements import conv + from sqlalchemy.sql.elements import quoted_name + from sqlalchemy.sql.elements import TextClause + from sqlalchemy.sql.functions import Function + from sqlalchemy.sql.schema import CheckConstraint + from sqlalchemy.sql.schema import Column + from sqlalchemy.sql.schema import Computed + from sqlalchemy.sql.schema import Constraint + from sqlalchemy.sql.schema import ForeignKeyConstraint + from sqlalchemy.sql.schema import Identity + from sqlalchemy.sql.schema import Index + from sqlalchemy.sql.schema import MetaData + from sqlalchemy.sql.schema import PrimaryKeyConstraint + from sqlalchemy.sql.schema import SchemaItem + from sqlalchemy.sql.schema import Table + from sqlalchemy.sql.schema import UniqueConstraint + from sqlalchemy.sql.selectable import TableClause + from sqlalchemy.sql.type_api import TypeEngine + + from ..autogenerate.rewriter import Rewriter + from ..runtime.migration import MigrationContext + from ..script.revision import _RevIdType + +_T = TypeVar("_T", bound=Any) +_AC = TypeVar("_AC", bound="AddConstraintOp") + + +class MigrateOperation: + """base class for migration command and organization objects. + + This system is part of the operation extensibility API. + + .. seealso:: + + :ref:`operation_objects` + + :ref:`operation_plugins` + + :ref:`customizing_revision` + + """ + + @util.memoized_property + def info(self) -> Dict[Any, Any]: + """A dictionary that may be used to store arbitrary information + along with this :class:`.MigrateOperation` object. + + """ + return {} + + _mutations: FrozenSet[Rewriter] = frozenset() + + def reverse(self) -> MigrateOperation: + raise NotImplementedError + + def to_diff_tuple(self) -> Tuple[Any, ...]: + raise NotImplementedError + + +class AddConstraintOp(MigrateOperation): + """Represent an add constraint operation.""" + + add_constraint_ops = util.Dispatcher() + + @property + def constraint_type(self) -> str: + raise NotImplementedError() + + @classmethod + def register_add_constraint( + cls, type_: str + ) -> Callable[[Type[_AC]], Type[_AC]]: + def go(klass: Type[_AC]) -> Type[_AC]: + cls.add_constraint_ops.dispatch_for(type_)(klass.from_constraint) + return klass + + return go + + @classmethod + def from_constraint(cls, constraint: Constraint) -> AddConstraintOp: + return cls.add_constraint_ops.dispatch(constraint.__visit_name__)( # type: ignore[no-any-return] # noqa: E501 + constraint + ) + + @abstractmethod + def to_constraint( + self, migration_context: Optional[MigrationContext] = None + ) -> Constraint: + pass + + def reverse(self) -> DropConstraintOp: + return DropConstraintOp.from_constraint(self.to_constraint()) + + def to_diff_tuple(self) -> Tuple[str, Constraint]: + return ("add_constraint", self.to_constraint()) + + +@Operations.register_operation("drop_constraint") +@BatchOperations.register_operation("drop_constraint", "batch_drop_constraint") +class DropConstraintOp(MigrateOperation): + """Represent a drop constraint operation.""" + + def __init__( + self, + constraint_name: Optional[sqla_compat._ConstraintNameDefined], + table_name: str, + type_: Optional[str] = None, + *, + schema: Optional[str] = None, + _reverse: Optional[AddConstraintOp] = None, + ) -> None: + self.constraint_name = constraint_name + self.table_name = table_name + self.constraint_type = type_ + self.schema = schema + self._reverse = _reverse + + def reverse(self) -> AddConstraintOp: + return AddConstraintOp.from_constraint(self.to_constraint()) + + def to_diff_tuple( + self, + ) -> Tuple[str, SchemaItem]: + if self.constraint_type == "foreignkey": + return ("remove_fk", self.to_constraint()) + else: + return ("remove_constraint", self.to_constraint()) + + @classmethod + def from_constraint(cls, constraint: Constraint) -> DropConstraintOp: + types = { + "unique_constraint": "unique", + "foreign_key_constraint": "foreignkey", + "primary_key_constraint": "primary", + "check_constraint": "check", + "column_check_constraint": "check", + "table_or_column_check_constraint": "check", + } + + constraint_table = sqla_compat._table_for_constraint(constraint) + return cls( + sqla_compat.constraint_name_or_none(constraint.name), + constraint_table.name, + schema=constraint_table.schema, + type_=types.get(constraint.__visit_name__), + _reverse=AddConstraintOp.from_constraint(constraint), + ) + + def to_constraint(self) -> Constraint: + if self._reverse is not None: + constraint = self._reverse.to_constraint() + constraint.name = self.constraint_name + constraint_table = sqla_compat._table_for_constraint(constraint) + constraint_table.name = self.table_name + constraint_table.schema = self.schema + + return constraint + else: + raise ValueError( + "constraint cannot be produced; " + "original constraint is not present" + ) + + @classmethod + def drop_constraint( + cls, + operations: Operations, + constraint_name: str, + table_name: str, + type_: Optional[str] = None, + *, + schema: Optional[str] = None, + ) -> None: + r"""Drop a constraint of the given name, typically via DROP CONSTRAINT. + + :param constraint_name: name of the constraint. + :param table_name: table name. + :param type\_: optional, required on MySQL. can be + 'foreignkey', 'primary', 'unique', or 'check'. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ + + op = cls(constraint_name, table_name, type_=type_, schema=schema) + return operations.invoke(op) + + @classmethod + def batch_drop_constraint( + cls, + operations: BatchOperations, + constraint_name: str, + type_: Optional[str] = None, + ) -> None: + """Issue a "drop constraint" instruction using the + current batch migration context. + + The batch form of this call omits the ``table_name`` and ``schema`` + arguments from the call. + + .. seealso:: + + :meth:`.Operations.drop_constraint` + + """ + op = cls( + constraint_name, + operations.impl.table_name, + type_=type_, + schema=operations.impl.schema, + ) + return operations.invoke(op) + + +@Operations.register_operation("create_primary_key") +@BatchOperations.register_operation( + "create_primary_key", "batch_create_primary_key" +) +@AddConstraintOp.register_add_constraint("primary_key_constraint") +class CreatePrimaryKeyOp(AddConstraintOp): + """Represent a create primary key operation.""" + + constraint_type = "primarykey" + + def __init__( + self, + constraint_name: Optional[sqla_compat._ConstraintNameDefined], + table_name: str, + columns: Sequence[str], + *, + schema: Optional[str] = None, + **kw: Any, + ) -> None: + self.constraint_name = constraint_name + self.table_name = table_name + self.columns = columns + self.schema = schema + self.kw = kw + + @classmethod + def from_constraint(cls, constraint: Constraint) -> CreatePrimaryKeyOp: + constraint_table = sqla_compat._table_for_constraint(constraint) + pk_constraint = cast("PrimaryKeyConstraint", constraint) + return cls( + sqla_compat.constraint_name_or_none(pk_constraint.name), + constraint_table.name, + pk_constraint.columns.keys(), + schema=constraint_table.schema, + **pk_constraint.dialect_kwargs, + ) + + def to_constraint( + self, migration_context: Optional[MigrationContext] = None + ) -> PrimaryKeyConstraint: + schema_obj = schemaobj.SchemaObjects(migration_context) + + return schema_obj.primary_key_constraint( + self.constraint_name, + self.table_name, + self.columns, + schema=self.schema, + **self.kw, + ) + + @classmethod + def create_primary_key( + cls, + operations: Operations, + constraint_name: Optional[str], + table_name: str, + columns: List[str], + *, + schema: Optional[str] = None, + ) -> None: + """Issue a "create primary key" instruction using the current + migration context. + + e.g.:: + + from alembic import op + + op.create_primary_key("pk_my_table", "my_table", ["id", "version"]) + + This internally generates a :class:`~sqlalchemy.schema.Table` object + containing the necessary columns, then generates a new + :class:`~sqlalchemy.schema.PrimaryKeyConstraint` + object which it then associates with the + :class:`~sqlalchemy.schema.Table`. + Any event listeners associated with this action will be fired + off normally. The :class:`~sqlalchemy.schema.AddConstraint` + construct is ultimately used to generate the ALTER statement. + + :param constraint_name: Name of the primary key constraint. The name + is necessary so that an ALTER statement can be emitted. For setups + that use an automated naming scheme such as that described at + :ref:`sqla:constraint_naming_conventions` + ``name`` here can be ``None``, as the event listener will + apply the name to the constraint object when it is associated + with the table. + :param table_name: String name of the target table. + :param columns: a list of string column names to be applied to the + primary key constraint. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ + op = cls(constraint_name, table_name, columns, schema=schema) + return operations.invoke(op) + + @classmethod + def batch_create_primary_key( + cls, + operations: BatchOperations, + constraint_name: str, + columns: List[str], + ) -> None: + """Issue a "create primary key" instruction using the + current batch migration context. + + The batch form of this call omits the ``table_name`` and ``schema`` + arguments from the call. + + .. seealso:: + + :meth:`.Operations.create_primary_key` + + """ + op = cls( + constraint_name, + operations.impl.table_name, + columns, + schema=operations.impl.schema, + ) + return operations.invoke(op) + + +@Operations.register_operation("create_unique_constraint") +@BatchOperations.register_operation( + "create_unique_constraint", "batch_create_unique_constraint" +) +@AddConstraintOp.register_add_constraint("unique_constraint") +class CreateUniqueConstraintOp(AddConstraintOp): + """Represent a create unique constraint operation.""" + + constraint_type = "unique" + + def __init__( + self, + constraint_name: Optional[sqla_compat._ConstraintNameDefined], + table_name: str, + columns: Sequence[str], + *, + schema: Optional[str] = None, + **kw: Any, + ) -> None: + self.constraint_name = constraint_name + self.table_name = table_name + self.columns = columns + self.schema = schema + self.kw = kw + + @classmethod + def from_constraint( + cls, constraint: Constraint + ) -> CreateUniqueConstraintOp: + constraint_table = sqla_compat._table_for_constraint(constraint) + + uq_constraint = cast("UniqueConstraint", constraint) + + kw: Dict[str, Any] = {} + if uq_constraint.deferrable: + kw["deferrable"] = uq_constraint.deferrable + if uq_constraint.initially: + kw["initially"] = uq_constraint.initially + kw.update(uq_constraint.dialect_kwargs) + return cls( + sqla_compat.constraint_name_or_none(uq_constraint.name), + constraint_table.name, + [c.name for c in uq_constraint.columns], + schema=constraint_table.schema, + **kw, + ) + + def to_constraint( + self, migration_context: Optional[MigrationContext] = None + ) -> UniqueConstraint: + schema_obj = schemaobj.SchemaObjects(migration_context) + return schema_obj.unique_constraint( + self.constraint_name, + self.table_name, + self.columns, + schema=self.schema, + **self.kw, + ) + + @classmethod + def create_unique_constraint( + cls, + operations: Operations, + constraint_name: Optional[str], + table_name: str, + columns: Sequence[str], + *, + schema: Optional[str] = None, + **kw: Any, + ) -> Any: + """Issue a "create unique constraint" instruction using the + current migration context. + + e.g.:: + + from alembic import op + op.create_unique_constraint("uq_user_name", "user", ["name"]) + + This internally generates a :class:`~sqlalchemy.schema.Table` object + containing the necessary columns, then generates a new + :class:`~sqlalchemy.schema.UniqueConstraint` + object which it then associates with the + :class:`~sqlalchemy.schema.Table`. + Any event listeners associated with this action will be fired + off normally. The :class:`~sqlalchemy.schema.AddConstraint` + construct is ultimately used to generate the ALTER statement. + + :param name: Name of the unique constraint. The name is necessary + so that an ALTER statement can be emitted. For setups that + use an automated naming scheme such as that described at + :ref:`sqla:constraint_naming_conventions`, + ``name`` here can be ``None``, as the event listener will + apply the name to the constraint object when it is associated + with the table. + :param table_name: String name of the source table. + :param columns: a list of string column names in the + source table. + :param deferrable: optional bool. If set, emit DEFERRABLE or + NOT DEFERRABLE when issuing DDL for this constraint. + :param initially: optional string. If set, emit INITIALLY + when issuing DDL for this constraint. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ + + op = cls(constraint_name, table_name, columns, schema=schema, **kw) + return operations.invoke(op) + + @classmethod + def batch_create_unique_constraint( + cls, + operations: BatchOperations, + constraint_name: str, + columns: Sequence[str], + **kw: Any, + ) -> Any: + """Issue a "create unique constraint" instruction using the + current batch migration context. + + The batch form of this call omits the ``source`` and ``schema`` + arguments from the call. + + .. seealso:: + + :meth:`.Operations.create_unique_constraint` + + """ + kw["schema"] = operations.impl.schema + op = cls(constraint_name, operations.impl.table_name, columns, **kw) + return operations.invoke(op) + + +@Operations.register_operation("create_foreign_key") +@BatchOperations.register_operation( + "create_foreign_key", "batch_create_foreign_key" +) +@AddConstraintOp.register_add_constraint("foreign_key_constraint") +class CreateForeignKeyOp(AddConstraintOp): + """Represent a create foreign key constraint operation.""" + + constraint_type = "foreignkey" + + def __init__( + self, + constraint_name: Optional[sqla_compat._ConstraintNameDefined], + source_table: str, + referent_table: str, + local_cols: List[str], + remote_cols: List[str], + **kw: Any, + ) -> None: + self.constraint_name = constraint_name + self.source_table = source_table + self.referent_table = referent_table + self.local_cols = local_cols + self.remote_cols = remote_cols + self.kw = kw + + def to_diff_tuple(self) -> Tuple[str, ForeignKeyConstraint]: + return ("add_fk", self.to_constraint()) + + @classmethod + def from_constraint(cls, constraint: Constraint) -> CreateForeignKeyOp: + fk_constraint = cast("ForeignKeyConstraint", constraint) + kw: Dict[str, Any] = {} + if fk_constraint.onupdate: + kw["onupdate"] = fk_constraint.onupdate + if fk_constraint.ondelete: + kw["ondelete"] = fk_constraint.ondelete + if fk_constraint.initially: + kw["initially"] = fk_constraint.initially + if fk_constraint.deferrable: + kw["deferrable"] = fk_constraint.deferrable + if fk_constraint.use_alter: + kw["use_alter"] = fk_constraint.use_alter + if fk_constraint.match: + kw["match"] = fk_constraint.match + + ( + source_schema, + source_table, + source_columns, + target_schema, + target_table, + target_columns, + onupdate, + ondelete, + deferrable, + initially, + ) = sqla_compat._fk_spec(fk_constraint) + + kw["source_schema"] = source_schema + kw["referent_schema"] = target_schema + kw.update(fk_constraint.dialect_kwargs) + return cls( + sqla_compat.constraint_name_or_none(fk_constraint.name), + source_table, + target_table, + source_columns, + target_columns, + **kw, + ) + + def to_constraint( + self, migration_context: Optional[MigrationContext] = None + ) -> ForeignKeyConstraint: + schema_obj = schemaobj.SchemaObjects(migration_context) + return schema_obj.foreign_key_constraint( + self.constraint_name, + self.source_table, + self.referent_table, + self.local_cols, + self.remote_cols, + **self.kw, + ) + + @classmethod + def create_foreign_key( + cls, + operations: Operations, + constraint_name: Optional[str], + source_table: str, + referent_table: str, + local_cols: List[str], + remote_cols: List[str], + *, + onupdate: Optional[str] = None, + ondelete: Optional[str] = None, + deferrable: Optional[bool] = None, + initially: Optional[str] = None, + match: Optional[str] = None, + source_schema: Optional[str] = None, + referent_schema: Optional[str] = None, + **dialect_kw: Any, + ) -> None: + """Issue a "create foreign key" instruction using the + current migration context. + + e.g.:: + + from alembic import op + + op.create_foreign_key( + "fk_user_address", + "address", + "user", + ["user_id"], + ["id"], + ) + + This internally generates a :class:`~sqlalchemy.schema.Table` object + containing the necessary columns, then generates a new + :class:`~sqlalchemy.schema.ForeignKeyConstraint` + object which it then associates with the + :class:`~sqlalchemy.schema.Table`. + Any event listeners associated with this action will be fired + off normally. The :class:`~sqlalchemy.schema.AddConstraint` + construct is ultimately used to generate the ALTER statement. + + :param constraint_name: Name of the foreign key constraint. The name + is necessary so that an ALTER statement can be emitted. For setups + that use an automated naming scheme such as that described at + :ref:`sqla:constraint_naming_conventions`, + ``name`` here can be ``None``, as the event listener will + apply the name to the constraint object when it is associated + with the table. + :param source_table: String name of the source table. + :param referent_table: String name of the destination table. + :param local_cols: a list of string column names in the + source table. + :param remote_cols: a list of string column names in the + remote table. + :param onupdate: Optional string. If set, emit ON UPDATE when + issuing DDL for this constraint. Typical values include CASCADE, + DELETE and RESTRICT. + :param ondelete: Optional string. If set, emit ON DELETE when + issuing DDL for this constraint. Typical values include CASCADE, + DELETE and RESTRICT. + :param deferrable: optional bool. If set, emit DEFERRABLE or NOT + DEFERRABLE when issuing DDL for this constraint. + :param source_schema: Optional schema name of the source table. + :param referent_schema: Optional schema name of the destination table. + + """ + + op = cls( + constraint_name, + source_table, + referent_table, + local_cols, + remote_cols, + onupdate=onupdate, + ondelete=ondelete, + deferrable=deferrable, + source_schema=source_schema, + referent_schema=referent_schema, + initially=initially, + match=match, + **dialect_kw, + ) + return operations.invoke(op) + + @classmethod + def batch_create_foreign_key( + cls, + operations: BatchOperations, + constraint_name: str, + referent_table: str, + local_cols: List[str], + remote_cols: List[str], + *, + referent_schema: Optional[str] = None, + onupdate: Optional[str] = None, + ondelete: Optional[str] = None, + deferrable: Optional[bool] = None, + initially: Optional[str] = None, + match: Optional[str] = None, + **dialect_kw: Any, + ) -> None: + """Issue a "create foreign key" instruction using the + current batch migration context. + + The batch form of this call omits the ``source`` and ``source_schema`` + arguments from the call. + + e.g.:: + + with batch_alter_table("address") as batch_op: + batch_op.create_foreign_key( + "fk_user_address", + "user", + ["user_id"], + ["id"], + ) + + .. seealso:: + + :meth:`.Operations.create_foreign_key` + + """ + op = cls( + constraint_name, + operations.impl.table_name, + referent_table, + local_cols, + remote_cols, + onupdate=onupdate, + ondelete=ondelete, + deferrable=deferrable, + source_schema=operations.impl.schema, + referent_schema=referent_schema, + initially=initially, + match=match, + **dialect_kw, + ) + return operations.invoke(op) + + +@Operations.register_operation("create_check_constraint") +@BatchOperations.register_operation( + "create_check_constraint", "batch_create_check_constraint" +) +@AddConstraintOp.register_add_constraint("check_constraint") +@AddConstraintOp.register_add_constraint("table_or_column_check_constraint") +@AddConstraintOp.register_add_constraint("column_check_constraint") +class CreateCheckConstraintOp(AddConstraintOp): + """Represent a create check constraint operation.""" + + constraint_type = "check" + + def __init__( + self, + constraint_name: Optional[sqla_compat._ConstraintNameDefined], + table_name: str, + condition: Union[str, TextClause, ColumnElement[Any]], + *, + schema: Optional[str] = None, + **kw: Any, + ) -> None: + self.constraint_name = constraint_name + self.table_name = table_name + self.condition = condition + self.schema = schema + self.kw = kw + + @classmethod + def from_constraint( + cls, constraint: Constraint + ) -> CreateCheckConstraintOp: + constraint_table = sqla_compat._table_for_constraint(constraint) + + ck_constraint = cast("CheckConstraint", constraint) + return cls( + sqla_compat.constraint_name_or_none(ck_constraint.name), + constraint_table.name, + cast("ColumnElement[Any]", ck_constraint.sqltext), + schema=constraint_table.schema, + **ck_constraint.dialect_kwargs, + ) + + def to_constraint( + self, migration_context: Optional[MigrationContext] = None + ) -> CheckConstraint: + schema_obj = schemaobj.SchemaObjects(migration_context) + return schema_obj.check_constraint( + self.constraint_name, + self.table_name, + self.condition, + schema=self.schema, + **self.kw, + ) + + @classmethod + def create_check_constraint( + cls, + operations: Operations, + constraint_name: Optional[str], + table_name: str, + condition: Union[str, ColumnElement[bool], TextClause], + *, + schema: Optional[str] = None, + **kw: Any, + ) -> None: + """Issue a "create check constraint" instruction using the + current migration context. + + e.g.:: + + from alembic import op + from sqlalchemy.sql import column, func + + op.create_check_constraint( + "ck_user_name_len", + "user", + func.len(column("name")) > 5, + ) + + CHECK constraints are usually against a SQL expression, so ad-hoc + table metadata is usually needed. The function will convert the given + arguments into a :class:`sqlalchemy.schema.CheckConstraint` bound + to an anonymous table in order to emit the CREATE statement. + + :param name: Name of the check constraint. The name is necessary + so that an ALTER statement can be emitted. For setups that + use an automated naming scheme such as that described at + :ref:`sqla:constraint_naming_conventions`, + ``name`` here can be ``None``, as the event listener will + apply the name to the constraint object when it is associated + with the table. + :param table_name: String name of the source table. + :param condition: SQL expression that's the condition of the + constraint. Can be a string or SQLAlchemy expression language + structure. + :param deferrable: optional bool. If set, emit DEFERRABLE or + NOT DEFERRABLE when issuing DDL for this constraint. + :param initially: optional string. If set, emit INITIALLY + when issuing DDL for this constraint. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ + op = cls(constraint_name, table_name, condition, schema=schema, **kw) + return operations.invoke(op) + + @classmethod + def batch_create_check_constraint( + cls, + operations: BatchOperations, + constraint_name: str, + condition: Union[str, ColumnElement[bool], TextClause], + **kw: Any, + ) -> None: + """Issue a "create check constraint" instruction using the + current batch migration context. + + The batch form of this call omits the ``source`` and ``schema`` + arguments from the call. + + .. seealso:: + + :meth:`.Operations.create_check_constraint` + + """ + op = cls( + constraint_name, + operations.impl.table_name, + condition, + schema=operations.impl.schema, + **kw, + ) + return operations.invoke(op) + + +@Operations.register_operation("create_index") +@BatchOperations.register_operation("create_index", "batch_create_index") +class CreateIndexOp(MigrateOperation): + """Represent a create index operation.""" + + def __init__( + self, + index_name: Optional[str], + table_name: str, + columns: Sequence[Union[str, TextClause, ColumnElement[Any]]], + *, + schema: Optional[str] = None, + unique: bool = False, + if_not_exists: Optional[bool] = None, + **kw: Any, + ) -> None: + self.index_name = index_name + self.table_name = table_name + self.columns = columns + self.schema = schema + self.unique = unique + self.if_not_exists = if_not_exists + self.kw = kw + + def reverse(self) -> DropIndexOp: + return DropIndexOp.from_index(self.to_index()) + + def to_diff_tuple(self) -> Tuple[str, Index]: + return ("add_index", self.to_index()) + + @classmethod + def from_index(cls, index: Index) -> CreateIndexOp: + assert index.table is not None + return cls( + index.name, + index.table.name, + index.expressions, + schema=index.table.schema, + unique=index.unique, + **index.kwargs, + ) + + def to_index( + self, migration_context: Optional[MigrationContext] = None + ) -> Index: + schema_obj = schemaobj.SchemaObjects(migration_context) + + idx = schema_obj.index( + self.index_name, + self.table_name, + self.columns, + schema=self.schema, + unique=self.unique, + **self.kw, + ) + return idx + + @classmethod + def create_index( + cls, + operations: Operations, + index_name: Optional[str], + table_name: str, + columns: Sequence[Union[str, TextClause, Function[Any]]], + *, + schema: Optional[str] = None, + unique: bool = False, + if_not_exists: Optional[bool] = None, + **kw: Any, + ) -> None: + r"""Issue a "create index" instruction using the current + migration context. + + e.g.:: + + from alembic import op + + op.create_index("ik_test", "t1", ["foo", "bar"]) + + Functional indexes can be produced by using the + :func:`sqlalchemy.sql.expression.text` construct:: + + from alembic import op + from sqlalchemy import text + + op.create_index("ik_test", "t1", [text("lower(foo)")]) + + :param index_name: name of the index. + :param table_name: name of the owning table. + :param columns: a list consisting of string column names and/or + :func:`~sqlalchemy.sql.expression.text` constructs. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + :param unique: If True, create a unique index. + + :param quote: Force quoting of this column's name on or off, + corresponding to ``True`` or ``False``. When left at its default + of ``None``, the column identifier will be quoted according to + whether the name is case sensitive (identifiers with at least one + upper case character are treated as case sensitive), or if it's a + reserved word. This flag is only needed to force quoting of a + reserved word which is not known by the SQLAlchemy dialect. + + :param if_not_exists: If True, adds IF NOT EXISTS operator when + creating the new index. + + .. versionadded:: 1.12.0 + + :param \**kw: Additional keyword arguments not mentioned above are + dialect specific, and passed in the form + ``_``. + See the documentation regarding an individual dialect at + :ref:`dialect_toplevel` for detail on documented arguments. + + """ + op = cls( + index_name, + table_name, + columns, + schema=schema, + unique=unique, + if_not_exists=if_not_exists, + **kw, + ) + return operations.invoke(op) + + @classmethod + def batch_create_index( + cls, + operations: BatchOperations, + index_name: str, + columns: List[str], + **kw: Any, + ) -> None: + """Issue a "create index" instruction using the + current batch migration context. + + .. seealso:: + + :meth:`.Operations.create_index` + + """ + + op = cls( + index_name, + operations.impl.table_name, + columns, + schema=operations.impl.schema, + **kw, + ) + return operations.invoke(op) + + +@Operations.register_operation("drop_index") +@BatchOperations.register_operation("drop_index", "batch_drop_index") +class DropIndexOp(MigrateOperation): + """Represent a drop index operation.""" + + def __init__( + self, + index_name: Union[quoted_name, str, conv], + table_name: Optional[str] = None, + *, + schema: Optional[str] = None, + if_exists: Optional[bool] = None, + _reverse: Optional[CreateIndexOp] = None, + **kw: Any, + ) -> None: + self.index_name = index_name + self.table_name = table_name + self.schema = schema + self.if_exists = if_exists + self._reverse = _reverse + self.kw = kw + + def to_diff_tuple(self) -> Tuple[str, Index]: + return ("remove_index", self.to_index()) + + def reverse(self) -> CreateIndexOp: + return CreateIndexOp.from_index(self.to_index()) + + @classmethod + def from_index(cls, index: Index) -> DropIndexOp: + assert index.table is not None + return cls( + index.name, # type: ignore[arg-type] + table_name=index.table.name, + schema=index.table.schema, + _reverse=CreateIndexOp.from_index(index), + unique=index.unique, + **index.kwargs, + ) + + def to_index( + self, migration_context: Optional[MigrationContext] = None + ) -> Index: + schema_obj = schemaobj.SchemaObjects(migration_context) + + # need a dummy column name here since SQLAlchemy + # 0.7.6 and further raises on Index with no columns + return schema_obj.index( + self.index_name, + self.table_name, + self._reverse.columns if self._reverse else ["x"], + schema=self.schema, + **self.kw, + ) + + @classmethod + def drop_index( + cls, + operations: Operations, + index_name: str, + table_name: Optional[str] = None, + *, + schema: Optional[str] = None, + if_exists: Optional[bool] = None, + **kw: Any, + ) -> None: + r"""Issue a "drop index" instruction using the current + migration context. + + e.g.:: + + drop_index("accounts") + + :param index_name: name of the index. + :param table_name: name of the owning table. Some + backends such as Microsoft SQL Server require this. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + :param if_exists: If True, adds IF EXISTS operator when + dropping the index. + + .. versionadded:: 1.12.0 + + :param \**kw: Additional keyword arguments not mentioned above are + dialect specific, and passed in the form + ``_``. + See the documentation regarding an individual dialect at + :ref:`dialect_toplevel` for detail on documented arguments. + + """ + op = cls( + index_name, + table_name=table_name, + schema=schema, + if_exists=if_exists, + **kw, + ) + return operations.invoke(op) + + @classmethod + def batch_drop_index( + cls, operations: BatchOperations, index_name: str, **kw: Any + ) -> None: + """Issue a "drop index" instruction using the + current batch migration context. + + .. seealso:: + + :meth:`.Operations.drop_index` + + """ + + op = cls( + index_name, + table_name=operations.impl.table_name, + schema=operations.impl.schema, + **kw, + ) + return operations.invoke(op) + + +@Operations.register_operation("create_table") +class CreateTableOp(MigrateOperation): + """Represent a create table operation.""" + + def __init__( + self, + table_name: str, + columns: Sequence[SchemaItem], + *, + schema: Optional[str] = None, + _namespace_metadata: Optional[MetaData] = None, + _constraints_included: bool = False, + **kw: Any, + ) -> None: + self.table_name = table_name + self.columns = columns + self.schema = schema + self.info = kw.pop("info", {}) + self.comment = kw.pop("comment", None) + self.prefixes = kw.pop("prefixes", None) + self.kw = kw + self._namespace_metadata = _namespace_metadata + self._constraints_included = _constraints_included + + def reverse(self) -> DropTableOp: + return DropTableOp.from_table( + self.to_table(), _namespace_metadata=self._namespace_metadata + ) + + def to_diff_tuple(self) -> Tuple[str, Table]: + return ("add_table", self.to_table()) + + @classmethod + def from_table( + cls, table: Table, *, _namespace_metadata: Optional[MetaData] = None + ) -> CreateTableOp: + if _namespace_metadata is None: + _namespace_metadata = table.metadata + + return cls( + table.name, + list(table.c) + list(table.constraints), + schema=table.schema, + _namespace_metadata=_namespace_metadata, + # given a Table() object, this Table will contain full Index() + # and UniqueConstraint objects already constructed in response to + # each unique=True / index=True flag on a Column. Carry this + # state along so that when we re-convert back into a Table, we + # skip unique=True/index=True so that these constraints are + # not doubled up. see #844 #848 + _constraints_included=True, + comment=table.comment, + info=dict(table.info), + prefixes=list(table._prefixes), + **table.kwargs, + ) + + def to_table( + self, migration_context: Optional[MigrationContext] = None + ) -> Table: + schema_obj = schemaobj.SchemaObjects(migration_context) + + return schema_obj.table( + self.table_name, + *self.columns, + schema=self.schema, + prefixes=list(self.prefixes) if self.prefixes else [], + comment=self.comment, + info=self.info.copy() if self.info else {}, + _constraints_included=self._constraints_included, + **self.kw, + ) + + @classmethod + def create_table( + cls, + operations: Operations, + table_name: str, + *columns: SchemaItem, + **kw: Any, + ) -> Table: + r"""Issue a "create table" instruction using the current migration + context. + + This directive receives an argument list similar to that of the + traditional :class:`sqlalchemy.schema.Table` construct, but without the + metadata:: + + from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column + from alembic import op + + op.create_table( + "account", + Column("id", INTEGER, primary_key=True), + Column("name", VARCHAR(50), nullable=False), + Column("description", NVARCHAR(200)), + Column("timestamp", TIMESTAMP, server_default=func.now()), + ) + + Note that :meth:`.create_table` accepts + :class:`~sqlalchemy.schema.Column` + constructs directly from the SQLAlchemy library. In particular, + default values to be created on the database side are + specified using the ``server_default`` parameter, and not + ``default`` which only specifies Python-side defaults:: + + from alembic import op + from sqlalchemy import Column, TIMESTAMP, func + + # specify "DEFAULT NOW" along with the "timestamp" column + op.create_table( + "account", + Column("id", INTEGER, primary_key=True), + Column("timestamp", TIMESTAMP, server_default=func.now()), + ) + + The function also returns a newly created + :class:`~sqlalchemy.schema.Table` object, corresponding to the table + specification given, which is suitable for + immediate SQL operations, in particular + :meth:`.Operations.bulk_insert`:: + + from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column + from alembic import op + + account_table = op.create_table( + "account", + Column("id", INTEGER, primary_key=True), + Column("name", VARCHAR(50), nullable=False), + Column("description", NVARCHAR(200)), + Column("timestamp", TIMESTAMP, server_default=func.now()), + ) + + op.bulk_insert( + account_table, + [ + {"name": "A1", "description": "account 1"}, + {"name": "A2", "description": "account 2"}, + ], + ) + + :param table_name: Name of the table + :param \*columns: collection of :class:`~sqlalchemy.schema.Column` + objects within + the table, as well as optional :class:`~sqlalchemy.schema.Constraint` + objects + and :class:`~.sqlalchemy.schema.Index` objects. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + :param \**kw: Other keyword arguments are passed to the underlying + :class:`sqlalchemy.schema.Table` object created for the command. + + :return: the :class:`~sqlalchemy.schema.Table` object corresponding + to the parameters given. + + """ + op = cls(table_name, columns, **kw) + return operations.invoke(op) + + +@Operations.register_operation("drop_table") +class DropTableOp(MigrateOperation): + """Represent a drop table operation.""" + + def __init__( + self, + table_name: str, + *, + schema: Optional[str] = None, + table_kw: Optional[MutableMapping[Any, Any]] = None, + _reverse: Optional[CreateTableOp] = None, + ) -> None: + self.table_name = table_name + self.schema = schema + self.table_kw = table_kw or {} + self.comment = self.table_kw.pop("comment", None) + self.info = self.table_kw.pop("info", None) + self.prefixes = self.table_kw.pop("prefixes", None) + self._reverse = _reverse + + def to_diff_tuple(self) -> Tuple[str, Table]: + return ("remove_table", self.to_table()) + + def reverse(self) -> CreateTableOp: + return CreateTableOp.from_table(self.to_table()) + + @classmethod + def from_table( + cls, table: Table, *, _namespace_metadata: Optional[MetaData] = None + ) -> DropTableOp: + return cls( + table.name, + schema=table.schema, + table_kw={ + "comment": table.comment, + "info": dict(table.info), + "prefixes": list(table._prefixes), + **table.kwargs, + }, + _reverse=CreateTableOp.from_table( + table, _namespace_metadata=_namespace_metadata + ), + ) + + def to_table( + self, migration_context: Optional[MigrationContext] = None + ) -> Table: + if self._reverse: + cols_and_constraints = self._reverse.columns + else: + cols_and_constraints = [] + + schema_obj = schemaobj.SchemaObjects(migration_context) + t = schema_obj.table( + self.table_name, + *cols_and_constraints, + comment=self.comment, + info=self.info.copy() if self.info else {}, + prefixes=list(self.prefixes) if self.prefixes else [], + schema=self.schema, + _constraints_included=self._reverse._constraints_included + if self._reverse + else False, + **self.table_kw, + ) + return t + + @classmethod + def drop_table( + cls, + operations: Operations, + table_name: str, + *, + schema: Optional[str] = None, + **kw: Any, + ) -> None: + r"""Issue a "drop table" instruction using the current + migration context. + + + e.g.:: + + drop_table("accounts") + + :param table_name: Name of the table + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + :param \**kw: Other keyword arguments are passed to the underlying + :class:`sqlalchemy.schema.Table` object created for the command. + + """ + op = cls(table_name, schema=schema, table_kw=kw) + operations.invoke(op) + + +class AlterTableOp(MigrateOperation): + """Represent an alter table operation.""" + + def __init__( + self, + table_name: str, + *, + schema: Optional[str] = None, + ) -> None: + self.table_name = table_name + self.schema = schema + + +@Operations.register_operation("rename_table") +class RenameTableOp(AlterTableOp): + """Represent a rename table operation.""" + + def __init__( + self, + old_table_name: str, + new_table_name: str, + *, + schema: Optional[str] = None, + ) -> None: + super().__init__(old_table_name, schema=schema) + self.new_table_name = new_table_name + + @classmethod + def rename_table( + cls, + operations: Operations, + old_table_name: str, + new_table_name: str, + *, + schema: Optional[str] = None, + ) -> None: + """Emit an ALTER TABLE to rename a table. + + :param old_table_name: old name. + :param new_table_name: new name. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ + op = cls(old_table_name, new_table_name, schema=schema) + return operations.invoke(op) + + +@Operations.register_operation("create_table_comment") +@BatchOperations.register_operation( + "create_table_comment", "batch_create_table_comment" +) +class CreateTableCommentOp(AlterTableOp): + """Represent a COMMENT ON `table` operation.""" + + def __init__( + self, + table_name: str, + comment: Optional[str], + *, + schema: Optional[str] = None, + existing_comment: Optional[str] = None, + ) -> None: + self.table_name = table_name + self.comment = comment + self.existing_comment = existing_comment + self.schema = schema + + @classmethod + def create_table_comment( + cls, + operations: Operations, + table_name: str, + comment: Optional[str], + *, + existing_comment: Optional[str] = None, + schema: Optional[str] = None, + ) -> None: + """Emit a COMMENT ON operation to set the comment for a table. + + :param table_name: string name of the target table. + :param comment: string value of the comment being registered against + the specified table. + :param existing_comment: String value of a comment + already registered on the specified table, used within autogenerate + so that the operation is reversible, but not required for direct + use. + + .. seealso:: + + :meth:`.Operations.drop_table_comment` + + :paramref:`.Operations.alter_column.comment` + + """ + + op = cls( + table_name, + comment, + existing_comment=existing_comment, + schema=schema, + ) + return operations.invoke(op) + + @classmethod + def batch_create_table_comment( + cls, + operations: BatchOperations, + comment: Optional[str], + *, + existing_comment: Optional[str] = None, + ) -> None: + """Emit a COMMENT ON operation to set the comment for a table + using the current batch migration context. + + :param comment: string value of the comment being registered against + the specified table. + :param existing_comment: String value of a comment + already registered on the specified table, used within autogenerate + so that the operation is reversible, but not required for direct + use. + + """ + + op = cls( + operations.impl.table_name, + comment, + existing_comment=existing_comment, + schema=operations.impl.schema, + ) + return operations.invoke(op) + + def reverse(self) -> Union[CreateTableCommentOp, DropTableCommentOp]: + """Reverses the COMMENT ON operation against a table.""" + if self.existing_comment is None: + return DropTableCommentOp( + self.table_name, + existing_comment=self.comment, + schema=self.schema, + ) + else: + return CreateTableCommentOp( + self.table_name, + self.existing_comment, + existing_comment=self.comment, + schema=self.schema, + ) + + def to_table( + self, migration_context: Optional[MigrationContext] = None + ) -> Table: + schema_obj = schemaobj.SchemaObjects(migration_context) + + return schema_obj.table( + self.table_name, schema=self.schema, comment=self.comment + ) + + def to_diff_tuple(self) -> Tuple[Any, ...]: + return ("add_table_comment", self.to_table(), self.existing_comment) + + +@Operations.register_operation("drop_table_comment") +@BatchOperations.register_operation( + "drop_table_comment", "batch_drop_table_comment" +) +class DropTableCommentOp(AlterTableOp): + """Represent an operation to remove the comment from a table.""" + + def __init__( + self, + table_name: str, + *, + schema: Optional[str] = None, + existing_comment: Optional[str] = None, + ) -> None: + self.table_name = table_name + self.existing_comment = existing_comment + self.schema = schema + + @classmethod + def drop_table_comment( + cls, + operations: Operations, + table_name: str, + *, + existing_comment: Optional[str] = None, + schema: Optional[str] = None, + ) -> None: + """Issue a "drop table comment" operation to + remove an existing comment set on a table. + + :param table_name: string name of the target table. + :param existing_comment: An optional string value of a comment already + registered on the specified table. + + .. seealso:: + + :meth:`.Operations.create_table_comment` + + :paramref:`.Operations.alter_column.comment` + + """ + + op = cls(table_name, existing_comment=existing_comment, schema=schema) + return operations.invoke(op) + + @classmethod + def batch_drop_table_comment( + cls, + operations: BatchOperations, + *, + existing_comment: Optional[str] = None, + ) -> None: + """Issue a "drop table comment" operation to + remove an existing comment set on a table using the current + batch operations context. + + :param existing_comment: An optional string value of a comment already + registered on the specified table. + + """ + + op = cls( + operations.impl.table_name, + existing_comment=existing_comment, + schema=operations.impl.schema, + ) + return operations.invoke(op) + + def reverse(self) -> CreateTableCommentOp: + """Reverses the COMMENT ON operation against a table.""" + return CreateTableCommentOp( + self.table_name, self.existing_comment, schema=self.schema + ) + + def to_table( + self, migration_context: Optional[MigrationContext] = None + ) -> Table: + schema_obj = schemaobj.SchemaObjects(migration_context) + + return schema_obj.table(self.table_name, schema=self.schema) + + def to_diff_tuple(self) -> Tuple[Any, ...]: + return ("remove_table_comment", self.to_table()) + + +@Operations.register_operation("alter_column") +@BatchOperations.register_operation("alter_column", "batch_alter_column") +class AlterColumnOp(AlterTableOp): + """Represent an alter column operation.""" + + def __init__( + self, + table_name: str, + column_name: str, + *, + schema: Optional[str] = None, + existing_type: Optional[Any] = None, + existing_server_default: Any = False, + existing_nullable: Optional[bool] = None, + existing_comment: Optional[str] = None, + modify_nullable: Optional[bool] = None, + modify_comment: Optional[Union[str, Literal[False]]] = False, + modify_server_default: Any = False, + modify_name: Optional[str] = None, + modify_type: Optional[Any] = None, + **kw: Any, + ) -> None: + super().__init__(table_name, schema=schema) + self.column_name = column_name + self.existing_type = existing_type + self.existing_server_default = existing_server_default + self.existing_nullable = existing_nullable + self.existing_comment = existing_comment + self.modify_nullable = modify_nullable + self.modify_comment = modify_comment + self.modify_server_default = modify_server_default + self.modify_name = modify_name + self.modify_type = modify_type + self.kw = kw + + def to_diff_tuple(self) -> Any: + col_diff = [] + schema, tname, cname = self.schema, self.table_name, self.column_name + + if self.modify_type is not None: + col_diff.append( + ( + "modify_type", + schema, + tname, + cname, + { + "existing_nullable": self.existing_nullable, + "existing_server_default": ( + self.existing_server_default + ), + "existing_comment": self.existing_comment, + }, + self.existing_type, + self.modify_type, + ) + ) + + if self.modify_nullable is not None: + col_diff.append( + ( + "modify_nullable", + schema, + tname, + cname, + { + "existing_type": self.existing_type, + "existing_server_default": ( + self.existing_server_default + ), + "existing_comment": self.existing_comment, + }, + self.existing_nullable, + self.modify_nullable, + ) + ) + + if self.modify_server_default is not False: + col_diff.append( + ( + "modify_default", + schema, + tname, + cname, + { + "existing_nullable": self.existing_nullable, + "existing_type": self.existing_type, + "existing_comment": self.existing_comment, + }, + self.existing_server_default, + self.modify_server_default, + ) + ) + + if self.modify_comment is not False: + col_diff.append( + ( + "modify_comment", + schema, + tname, + cname, + { + "existing_nullable": self.existing_nullable, + "existing_type": self.existing_type, + "existing_server_default": ( + self.existing_server_default + ), + }, + self.existing_comment, + self.modify_comment, + ) + ) + + return col_diff + + def has_changes(self) -> bool: + hc1 = ( + self.modify_nullable is not None + or self.modify_server_default is not False + or self.modify_type is not None + or self.modify_comment is not False + ) + if hc1: + return True + for kw in self.kw: + if kw.startswith("modify_"): + return True + else: + return False + + def reverse(self) -> AlterColumnOp: + kw = self.kw.copy() + kw["existing_type"] = self.existing_type + kw["existing_nullable"] = self.existing_nullable + kw["existing_server_default"] = self.existing_server_default + kw["existing_comment"] = self.existing_comment + if self.modify_type is not None: + kw["modify_type"] = self.modify_type + if self.modify_nullable is not None: + kw["modify_nullable"] = self.modify_nullable + if self.modify_server_default is not False: + kw["modify_server_default"] = self.modify_server_default + if self.modify_comment is not False: + kw["modify_comment"] = self.modify_comment + + # TODO: make this a little simpler + all_keys = { + m.group(1) + for m in [re.match(r"^(?:existing_|modify_)(.+)$", k) for k in kw] + if m + } + + for k in all_keys: + if "modify_%s" % k in kw: + swap = kw["existing_%s" % k] + kw["existing_%s" % k] = kw["modify_%s" % k] + kw["modify_%s" % k] = swap + + return self.__class__( + self.table_name, self.column_name, schema=self.schema, **kw + ) + + @classmethod + def alter_column( + cls, + operations: Operations, + table_name: str, + column_name: str, + *, + nullable: Optional[bool] = None, + comment: Optional[Union[str, Literal[False]]] = False, + server_default: Any = False, + new_column_name: Optional[str] = None, + type_: Optional[Union[TypeEngine[Any], Type[TypeEngine[Any]]]] = None, + existing_type: Optional[ + Union[TypeEngine[Any], Type[TypeEngine[Any]]] + ] = None, + existing_server_default: Optional[ + Union[str, bool, Identity, Computed] + ] = False, + existing_nullable: Optional[bool] = None, + existing_comment: Optional[str] = None, + schema: Optional[str] = None, + **kw: Any, + ) -> None: + r"""Issue an "alter column" instruction using the + current migration context. + + Generally, only that aspect of the column which + is being changed, i.e. name, type, nullability, + default, needs to be specified. Multiple changes + can also be specified at once and the backend should + "do the right thing", emitting each change either + separately or together as the backend allows. + + MySQL has special requirements here, since MySQL + cannot ALTER a column without a full specification. + When producing MySQL-compatible migration files, + it is recommended that the ``existing_type``, + ``existing_server_default``, and ``existing_nullable`` + parameters be present, if not being altered. + + Type changes which are against the SQLAlchemy + "schema" types :class:`~sqlalchemy.types.Boolean` + and :class:`~sqlalchemy.types.Enum` may also + add or drop constraints which accompany those + types on backends that don't support them natively. + The ``existing_type`` argument is + used in this case to identify and remove a previous + constraint that was bound to the type object. + + :param table_name: string name of the target table. + :param column_name: string name of the target column, + as it exists before the operation begins. + :param nullable: Optional; specify ``True`` or ``False`` + to alter the column's nullability. + :param server_default: Optional; specify a string + SQL expression, :func:`~sqlalchemy.sql.expression.text`, + or :class:`~sqlalchemy.schema.DefaultClause` to indicate + an alteration to the column's default value. + Set to ``None`` to have the default removed. + :param comment: optional string text of a new comment to add to the + column. + :param new_column_name: Optional; specify a string name here to + indicate the new name within a column rename operation. + :param type\_: Optional; a :class:`~sqlalchemy.types.TypeEngine` + type object to specify a change to the column's type. + For SQLAlchemy types that also indicate a constraint (i.e. + :class:`~sqlalchemy.types.Boolean`, :class:`~sqlalchemy.types.Enum`), + the constraint is also generated. + :param autoincrement: set the ``AUTO_INCREMENT`` flag of the column; + currently understood by the MySQL dialect. + :param existing_type: Optional; a + :class:`~sqlalchemy.types.TypeEngine` + type object to specify the previous type. This + is required for all MySQL column alter operations that + don't otherwise specify a new type, as well as for + when nullability is being changed on a SQL Server + column. It is also used if the type is a so-called + SQLAlchemy "schema" type which may define a constraint (i.e. + :class:`~sqlalchemy.types.Boolean`, + :class:`~sqlalchemy.types.Enum`), + so that the constraint can be dropped. + :param existing_server_default: Optional; The existing + default value of the column. Required on MySQL if + an existing default is not being changed; else MySQL + removes the default. + :param existing_nullable: Optional; the existing nullability + of the column. Required on MySQL if the existing nullability + is not being changed; else MySQL sets this to NULL. + :param existing_autoincrement: Optional; the existing autoincrement + of the column. Used for MySQL's system of altering a column + that specifies ``AUTO_INCREMENT``. + :param existing_comment: string text of the existing comment on the + column to be maintained. Required on MySQL if the existing comment + on the column is not being changed. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + :param postgresql_using: String argument which will indicate a + SQL expression to render within the Postgresql-specific USING clause + within ALTER COLUMN. This string is taken directly as raw SQL which + must explicitly include any necessary quoting or escaping of tokens + within the expression. + + """ + + alt = cls( + table_name, + column_name, + schema=schema, + existing_type=existing_type, + existing_server_default=existing_server_default, + existing_nullable=existing_nullable, + existing_comment=existing_comment, + modify_name=new_column_name, + modify_type=type_, + modify_server_default=server_default, + modify_nullable=nullable, + modify_comment=comment, + **kw, + ) + + return operations.invoke(alt) + + @classmethod + def batch_alter_column( + cls, + operations: BatchOperations, + column_name: str, + *, + nullable: Optional[bool] = None, + comment: Optional[Union[str, Literal[False]]] = False, + server_default: Any = False, + new_column_name: Optional[str] = None, + type_: Optional[Union[TypeEngine[Any], Type[TypeEngine[Any]]]] = None, + existing_type: Optional[ + Union[TypeEngine[Any], Type[TypeEngine[Any]]] + ] = None, + existing_server_default: Optional[ + Union[str, bool, Identity, Computed] + ] = False, + existing_nullable: Optional[bool] = None, + existing_comment: Optional[str] = None, + insert_before: Optional[str] = None, + insert_after: Optional[str] = None, + **kw: Any, + ) -> None: + """Issue an "alter column" instruction using the current + batch migration context. + + Parameters are the same as that of :meth:`.Operations.alter_column`, + as well as the following option(s): + + :param insert_before: String name of an existing column which this + column should be placed before, when creating the new table. + + :param insert_after: String name of an existing column which this + column should be placed after, when creating the new table. If + both :paramref:`.BatchOperations.alter_column.insert_before` + and :paramref:`.BatchOperations.alter_column.insert_after` are + omitted, the column is inserted after the last existing column + in the table. + + .. seealso:: + + :meth:`.Operations.alter_column` + + + """ + alt = cls( + operations.impl.table_name, + column_name, + schema=operations.impl.schema, + existing_type=existing_type, + existing_server_default=existing_server_default, + existing_nullable=existing_nullable, + existing_comment=existing_comment, + modify_name=new_column_name, + modify_type=type_, + modify_server_default=server_default, + modify_nullable=nullable, + modify_comment=comment, + insert_before=insert_before, + insert_after=insert_after, + **kw, + ) + + return operations.invoke(alt) + + +@Operations.register_operation("add_column") +@BatchOperations.register_operation("add_column", "batch_add_column") +class AddColumnOp(AlterTableOp): + """Represent an add column operation.""" + + def __init__( + self, + table_name: str, + column: Column[Any], + *, + schema: Optional[str] = None, + **kw: Any, + ) -> None: + super().__init__(table_name, schema=schema) + self.column = column + self.kw = kw + + def reverse(self) -> DropColumnOp: + return DropColumnOp.from_column_and_tablename( + self.schema, self.table_name, self.column + ) + + def to_diff_tuple( + self, + ) -> Tuple[str, Optional[str], str, Column[Any]]: + return ("add_column", self.schema, self.table_name, self.column) + + def to_column(self) -> Column[Any]: + return self.column + + @classmethod + def from_column(cls, col: Column[Any]) -> AddColumnOp: + return cls(col.table.name, col, schema=col.table.schema) + + @classmethod + def from_column_and_tablename( + cls, + schema: Optional[str], + tname: str, + col: Column[Any], + ) -> AddColumnOp: + return cls(tname, col, schema=schema) + + @classmethod + def add_column( + cls, + operations: Operations, + table_name: str, + column: Column[Any], + *, + schema: Optional[str] = None, + ) -> None: + """Issue an "add column" instruction using the current + migration context. + + e.g.:: + + from alembic import op + from sqlalchemy import Column, String + + op.add_column("organization", Column("name", String())) + + The :meth:`.Operations.add_column` method typically corresponds + to the SQL command "ALTER TABLE... ADD COLUMN". Within the scope + of this command, the column's name, datatype, nullability, + and optional server-generated defaults may be indicated. + + .. note:: + + With the exception of NOT NULL constraints or single-column FOREIGN + KEY constraints, other kinds of constraints such as PRIMARY KEY, + UNIQUE or CHECK constraints **cannot** be generated using this + method; for these constraints, refer to operations such as + :meth:`.Operations.create_primary_key` and + :meth:`.Operations.create_check_constraint`. In particular, the + following :class:`~sqlalchemy.schema.Column` parameters are + **ignored**: + + * :paramref:`~sqlalchemy.schema.Column.primary_key` - SQL databases + typically do not support an ALTER operation that can add + individual columns one at a time to an existing primary key + constraint, therefore it's less ambiguous to use the + :meth:`.Operations.create_primary_key` method, which assumes no + existing primary key constraint is present. + * :paramref:`~sqlalchemy.schema.Column.unique` - use the + :meth:`.Operations.create_unique_constraint` method + * :paramref:`~sqlalchemy.schema.Column.index` - use the + :meth:`.Operations.create_index` method + + + The provided :class:`~sqlalchemy.schema.Column` object may include a + :class:`~sqlalchemy.schema.ForeignKey` constraint directive, + referencing a remote table name. For this specific type of constraint, + Alembic will automatically emit a second ALTER statement in order to + add the single-column FOREIGN KEY constraint separately:: + + from alembic import op + from sqlalchemy import Column, INTEGER, ForeignKey + + op.add_column( + "organization", + Column("account_id", INTEGER, ForeignKey("accounts.id")), + ) + + The column argument passed to :meth:`.Operations.add_column` is a + :class:`~sqlalchemy.schema.Column` construct, used in the same way it's + used in SQLAlchemy. In particular, values or functions to be indicated + as producing the column's default value on the database side are + specified using the ``server_default`` parameter, and not ``default`` + which only specifies Python-side defaults:: + + from alembic import op + from sqlalchemy import Column, TIMESTAMP, func + + # specify "DEFAULT NOW" along with the column add + op.add_column( + "account", + Column("timestamp", TIMESTAMP, server_default=func.now()), + ) + + :param table_name: String name of the parent table. + :param column: a :class:`sqlalchemy.schema.Column` object + representing the new column. + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + + """ + + op = cls(table_name, column, schema=schema) + return operations.invoke(op) + + @classmethod + def batch_add_column( + cls, + operations: BatchOperations, + column: Column[Any], + *, + insert_before: Optional[str] = None, + insert_after: Optional[str] = None, + ) -> None: + """Issue an "add column" instruction using the current + batch migration context. + + .. seealso:: + + :meth:`.Operations.add_column` + + """ + + kw = {} + if insert_before: + kw["insert_before"] = insert_before + if insert_after: + kw["insert_after"] = insert_after + + op = cls( + operations.impl.table_name, + column, + schema=operations.impl.schema, + **kw, + ) + return operations.invoke(op) + + +@Operations.register_operation("drop_column") +@BatchOperations.register_operation("drop_column", "batch_drop_column") +class DropColumnOp(AlterTableOp): + """Represent a drop column operation.""" + + def __init__( + self, + table_name: str, + column_name: str, + *, + schema: Optional[str] = None, + _reverse: Optional[AddColumnOp] = None, + **kw: Any, + ) -> None: + super().__init__(table_name, schema=schema) + self.column_name = column_name + self.kw = kw + self._reverse = _reverse + + def to_diff_tuple( + self, + ) -> Tuple[str, Optional[str], str, Column[Any]]: + return ( + "remove_column", + self.schema, + self.table_name, + self.to_column(), + ) + + def reverse(self) -> AddColumnOp: + if self._reverse is None: + raise ValueError( + "operation is not reversible; " + "original column is not present" + ) + + return AddColumnOp.from_column_and_tablename( + self.schema, self.table_name, self._reverse.column + ) + + @classmethod + def from_column_and_tablename( + cls, + schema: Optional[str], + tname: str, + col: Column[Any], + ) -> DropColumnOp: + return cls( + tname, + col.name, + schema=schema, + _reverse=AddColumnOp.from_column_and_tablename(schema, tname, col), + ) + + def to_column( + self, migration_context: Optional[MigrationContext] = None + ) -> Column[Any]: + if self._reverse is not None: + return self._reverse.column + schema_obj = schemaobj.SchemaObjects(migration_context) + return schema_obj.column(self.column_name, NULLTYPE) + + @classmethod + def drop_column( + cls, + operations: Operations, + table_name: str, + column_name: str, + *, + schema: Optional[str] = None, + **kw: Any, + ) -> None: + """Issue a "drop column" instruction using the current + migration context. + + e.g.:: + + drop_column("organization", "account_id") + + :param table_name: name of table + :param column_name: name of column + :param schema: Optional schema name to operate within. To control + quoting of the schema outside of the default behavior, use + the SQLAlchemy construct + :class:`~sqlalchemy.sql.elements.quoted_name`. + :param mssql_drop_check: Optional boolean. When ``True``, on + Microsoft SQL Server only, first + drop the CHECK constraint on the column using a + SQL-script-compatible + block that selects into a @variable from sys.check_constraints, + then exec's a separate DROP CONSTRAINT for that constraint. + :param mssql_drop_default: Optional boolean. When ``True``, on + Microsoft SQL Server only, first + drop the DEFAULT constraint on the column using a + SQL-script-compatible + block that selects into a @variable from sys.default_constraints, + then exec's a separate DROP CONSTRAINT for that default. + :param mssql_drop_foreign_key: Optional boolean. When ``True``, on + Microsoft SQL Server only, first + drop a single FOREIGN KEY constraint on the column using a + SQL-script-compatible + block that selects into a @variable from + sys.foreign_keys/sys.foreign_key_columns, + then exec's a separate DROP CONSTRAINT for that default. Only + works if the column has exactly one FK constraint which refers to + it, at the moment. + + """ + + op = cls(table_name, column_name, schema=schema, **kw) + return operations.invoke(op) + + @classmethod + def batch_drop_column( + cls, operations: BatchOperations, column_name: str, **kw: Any + ) -> None: + """Issue a "drop column" instruction using the current + batch migration context. + + .. seealso:: + + :meth:`.Operations.drop_column` + + """ + op = cls( + operations.impl.table_name, + column_name, + schema=operations.impl.schema, + **kw, + ) + return operations.invoke(op) + + +@Operations.register_operation("bulk_insert") +class BulkInsertOp(MigrateOperation): + """Represent a bulk insert operation.""" + + def __init__( + self, + table: Union[Table, TableClause], + rows: List[Dict[str, Any]], + *, + multiinsert: bool = True, + ) -> None: + self.table = table + self.rows = rows + self.multiinsert = multiinsert + + @classmethod + def bulk_insert( + cls, + operations: Operations, + table: Union[Table, TableClause], + rows: List[Dict[str, Any]], + *, + multiinsert: bool = True, + ) -> None: + """Issue a "bulk insert" operation using the current + migration context. + + This provides a means of representing an INSERT of multiple rows + which works equally well in the context of executing on a live + connection as well as that of generating a SQL script. In the + case of a SQL script, the values are rendered inline into the + statement. + + e.g.:: + + from alembic import op + from datetime import date + from sqlalchemy.sql import table, column + from sqlalchemy import String, Integer, Date + + # Create an ad-hoc table to use for the insert statement. + accounts_table = table( + "account", + column("id", Integer), + column("name", String), + column("create_date", Date), + ) + + op.bulk_insert( + accounts_table, + [ + { + "id": 1, + "name": "John Smith", + "create_date": date(2010, 10, 5), + }, + { + "id": 2, + "name": "Ed Williams", + "create_date": date(2007, 5, 27), + }, + { + "id": 3, + "name": "Wendy Jones", + "create_date": date(2008, 8, 15), + }, + ], + ) + + When using --sql mode, some datatypes may not render inline + automatically, such as dates and other special types. When this + issue is present, :meth:`.Operations.inline_literal` may be used:: + + op.bulk_insert( + accounts_table, + [ + { + "id": 1, + "name": "John Smith", + "create_date": op.inline_literal("2010-10-05"), + }, + { + "id": 2, + "name": "Ed Williams", + "create_date": op.inline_literal("2007-05-27"), + }, + { + "id": 3, + "name": "Wendy Jones", + "create_date": op.inline_literal("2008-08-15"), + }, + ], + multiinsert=False, + ) + + When using :meth:`.Operations.inline_literal` in conjunction with + :meth:`.Operations.bulk_insert`, in order for the statement to work + in "online" (e.g. non --sql) mode, the + :paramref:`~.Operations.bulk_insert.multiinsert` + flag should be set to ``False``, which will have the effect of + individual INSERT statements being emitted to the database, each + with a distinct VALUES clause, so that the "inline" values can + still be rendered, rather than attempting to pass the values + as bound parameters. + + :param table: a table object which represents the target of the INSERT. + + :param rows: a list of dictionaries indicating rows. + + :param multiinsert: when at its default of True and --sql mode is not + enabled, the INSERT statement will be executed using + "executemany()" style, where all elements in the list of + dictionaries are passed as bound parameters in a single + list. Setting this to False results in individual INSERT + statements being emitted per parameter set, and is needed + in those cases where non-literal values are present in the + parameter sets. + + """ + + op = cls(table, rows, multiinsert=multiinsert) + operations.invoke(op) + + +@Operations.register_operation("execute") +@BatchOperations.register_operation("execute", "batch_execute") +class ExecuteSQLOp(MigrateOperation): + """Represent an execute SQL operation.""" + + def __init__( + self, + sqltext: Union[Executable, str], + *, + execution_options: Optional[dict[str, Any]] = None, + ) -> None: + self.sqltext = sqltext + self.execution_options = execution_options + + @classmethod + def execute( + cls, + operations: Operations, + sqltext: Union[Executable, str], + *, + execution_options: Optional[dict[str, Any]] = None, + ) -> None: + r"""Execute the given SQL using the current migration context. + + The given SQL can be a plain string, e.g.:: + + op.execute("INSERT INTO table (foo) VALUES ('some value')") + + Or it can be any kind of Core SQL Expression construct, such as + below where we use an update construct:: + + from sqlalchemy.sql import table, column + from sqlalchemy import String + from alembic import op + + account = table("account", column("name", String)) + op.execute( + account.update() + .where(account.c.name == op.inline_literal("account 1")) + .values({"name": op.inline_literal("account 2")}) + ) + + Above, we made use of the SQLAlchemy + :func:`sqlalchemy.sql.expression.table` and + :func:`sqlalchemy.sql.expression.column` constructs to make a brief, + ad-hoc table construct just for our UPDATE statement. A full + :class:`~sqlalchemy.schema.Table` construct of course works perfectly + fine as well, though note it's a recommended practice to at least + ensure the definition of a table is self-contained within the migration + script, rather than imported from a module that may break compatibility + with older migrations. + + In a SQL script context, the statement is emitted directly to the + output stream. There is *no* return result, however, as this + function is oriented towards generating a change script + that can run in "offline" mode. Additionally, parameterized + statements are discouraged here, as they *will not work* in offline + mode. Above, we use :meth:`.inline_literal` where parameters are + to be used. + + For full interaction with a connected database where parameters can + also be used normally, use the "bind" available from the context:: + + from alembic import op + + connection = op.get_bind() + + connection.execute( + account.update() + .where(account.c.name == "account 1") + .values({"name": "account 2"}) + ) + + Additionally, when passing the statement as a plain string, it is first + coerced into a :func:`sqlalchemy.sql.expression.text` construct + before being passed along. In the less likely case that the + literal SQL string contains a colon, it must be escaped with a + backslash, as:: + + op.execute(r"INSERT INTO table (foo) VALUES ('\:colon_value')") + + + :param sqltext: Any legal SQLAlchemy expression, including: + + * a string + * a :func:`sqlalchemy.sql.expression.text` construct. + * a :func:`sqlalchemy.sql.expression.insert` construct. + * a :func:`sqlalchemy.sql.expression.update` construct. + * a :func:`sqlalchemy.sql.expression.delete` construct. + * Any "executable" described in SQLAlchemy Core documentation, + noting that no result set is returned. + + .. note:: when passing a plain string, the statement is coerced into + a :func:`sqlalchemy.sql.expression.text` construct. This construct + considers symbols with colons, e.g. ``:foo`` to be bound parameters. + To avoid this, ensure that colon symbols are escaped, e.g. + ``\:foo``. + + :param execution_options: Optional dictionary of + execution options, will be passed to + :meth:`sqlalchemy.engine.Connection.execution_options`. + """ + op = cls(sqltext, execution_options=execution_options) + return operations.invoke(op) + + @classmethod + def batch_execute( + cls, + operations: Operations, + sqltext: Union[Executable, str], + *, + execution_options: Optional[dict[str, Any]] = None, + ) -> None: + """Execute the given SQL using the current migration context. + + .. seealso:: + + :meth:`.Operations.execute` + + """ + return cls.execute( + operations, sqltext, execution_options=execution_options + ) + + def to_diff_tuple(self) -> Tuple[str, Union[Executable, str]]: + return ("execute", self.sqltext) + + +class OpContainer(MigrateOperation): + """Represent a sequence of operations operation.""" + + def __init__(self, ops: Sequence[MigrateOperation] = ()) -> None: + self.ops = list(ops) + + def is_empty(self) -> bool: + return not self.ops + + def as_diffs(self) -> Any: + return list(OpContainer._ops_as_diffs(self)) + + @classmethod + def _ops_as_diffs( + cls, migrations: OpContainer + ) -> Iterator[Tuple[Any, ...]]: + for op in migrations.ops: + if hasattr(op, "ops"): + yield from cls._ops_as_diffs(cast("OpContainer", op)) + else: + yield op.to_diff_tuple() + + +class ModifyTableOps(OpContainer): + """Contains a sequence of operations that all apply to a single Table.""" + + def __init__( + self, + table_name: str, + ops: Sequence[MigrateOperation], + *, + schema: Optional[str] = None, + ) -> None: + super().__init__(ops) + self.table_name = table_name + self.schema = schema + + def reverse(self) -> ModifyTableOps: + return ModifyTableOps( + self.table_name, + ops=list(reversed([op.reverse() for op in self.ops])), + schema=self.schema, + ) + + +class UpgradeOps(OpContainer): + """contains a sequence of operations that would apply to the + 'upgrade' stream of a script. + + .. seealso:: + + :ref:`customizing_revision` + + """ + + def __init__( + self, + ops: Sequence[MigrateOperation] = (), + upgrade_token: str = "upgrades", + ) -> None: + super().__init__(ops=ops) + self.upgrade_token = upgrade_token + + def reverse_into(self, downgrade_ops: DowngradeOps) -> DowngradeOps: + downgrade_ops.ops[:] = list( + reversed([op.reverse() for op in self.ops]) + ) + return downgrade_ops + + def reverse(self) -> DowngradeOps: + return self.reverse_into(DowngradeOps(ops=[])) + + +class DowngradeOps(OpContainer): + """contains a sequence of operations that would apply to the + 'downgrade' stream of a script. + + .. seealso:: + + :ref:`customizing_revision` + + """ + + def __init__( + self, + ops: Sequence[MigrateOperation] = (), + downgrade_token: str = "downgrades", + ) -> None: + super().__init__(ops=ops) + self.downgrade_token = downgrade_token + + def reverse(self) -> UpgradeOps: + return UpgradeOps( + ops=list(reversed([op.reverse() for op in self.ops])) + ) + + +class MigrationScript(MigrateOperation): + """represents a migration script. + + E.g. when autogenerate encounters this object, this corresponds to the + production of an actual script file. + + A normal :class:`.MigrationScript` object would contain a single + :class:`.UpgradeOps` and a single :class:`.DowngradeOps` directive. + These are accessible via the ``.upgrade_ops`` and ``.downgrade_ops`` + attributes. + + In the case of an autogenerate operation that runs multiple times, + such as the multiple database example in the "multidb" template, + the ``.upgrade_ops`` and ``.downgrade_ops`` attributes are disabled, + and instead these objects should be accessed via the ``.upgrade_ops_list`` + and ``.downgrade_ops_list`` list-based attributes. These latter + attributes are always available at the very least as single-element lists. + + .. seealso:: + + :ref:`customizing_revision` + + """ + + _needs_render: Optional[bool] + _upgrade_ops: List[UpgradeOps] + _downgrade_ops: List[DowngradeOps] + + def __init__( + self, + rev_id: Optional[str], + upgrade_ops: UpgradeOps, + downgrade_ops: DowngradeOps, + *, + message: Optional[str] = None, + imports: Set[str] = set(), + head: Optional[str] = None, + splice: Optional[bool] = None, + branch_label: Optional[_RevIdType] = None, + version_path: Optional[str] = None, + depends_on: Optional[_RevIdType] = None, + ) -> None: + self.rev_id = rev_id + self.message = message + self.imports = imports + self.head = head + self.splice = splice + self.branch_label = branch_label + self.version_path = version_path + self.depends_on = depends_on + self.upgrade_ops = upgrade_ops + self.downgrade_ops = downgrade_ops + + @property + def upgrade_ops(self) -> Optional[UpgradeOps]: + """An instance of :class:`.UpgradeOps`. + + .. seealso:: + + :attr:`.MigrationScript.upgrade_ops_list` + """ + if len(self._upgrade_ops) > 1: + raise ValueError( + "This MigrationScript instance has a multiple-entry " + "list for UpgradeOps; please use the " + "upgrade_ops_list attribute." + ) + elif not self._upgrade_ops: + return None + else: + return self._upgrade_ops[0] + + @upgrade_ops.setter + def upgrade_ops( + self, upgrade_ops: Union[UpgradeOps, List[UpgradeOps]] + ) -> None: + self._upgrade_ops = util.to_list(upgrade_ops) + for elem in self._upgrade_ops: + assert isinstance(elem, UpgradeOps) + + @property + def downgrade_ops(self) -> Optional[DowngradeOps]: + """An instance of :class:`.DowngradeOps`. + + .. seealso:: + + :attr:`.MigrationScript.downgrade_ops_list` + """ + if len(self._downgrade_ops) > 1: + raise ValueError( + "This MigrationScript instance has a multiple-entry " + "list for DowngradeOps; please use the " + "downgrade_ops_list attribute." + ) + elif not self._downgrade_ops: + return None + else: + return self._downgrade_ops[0] + + @downgrade_ops.setter + def downgrade_ops( + self, downgrade_ops: Union[DowngradeOps, List[DowngradeOps]] + ) -> None: + self._downgrade_ops = util.to_list(downgrade_ops) + for elem in self._downgrade_ops: + assert isinstance(elem, DowngradeOps) + + @property + def upgrade_ops_list(self) -> List[UpgradeOps]: + """A list of :class:`.UpgradeOps` instances. + + This is used in place of the :attr:`.MigrationScript.upgrade_ops` + attribute when dealing with a revision operation that does + multiple autogenerate passes. + + """ + return self._upgrade_ops + + @property + def downgrade_ops_list(self) -> List[DowngradeOps]: + """A list of :class:`.DowngradeOps` instances. + + This is used in place of the :attr:`.MigrationScript.downgrade_ops` + attribute when dealing with a revision operation that does + multiple autogenerate passes. + + """ + return self._downgrade_ops diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/schemaobj.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/schemaobj.py new file mode 100644 index 0000000000000000000000000000000000000000..32b26e9b9d6471c7c663e732a2cfeb35e9eb4bd6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/schemaobj.py @@ -0,0 +1,288 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +from typing import Any +from typing import Dict +from typing import List +from typing import Optional +from typing import Sequence +from typing import Tuple +from typing import TYPE_CHECKING +from typing import Union + +from sqlalchemy import schema as sa_schema +from sqlalchemy.sql.schema import Column +from sqlalchemy.sql.schema import Constraint +from sqlalchemy.sql.schema import Index +from sqlalchemy.types import Integer +from sqlalchemy.types import NULLTYPE + +from .. import util +from ..util import sqla_compat + +if TYPE_CHECKING: + from sqlalchemy.sql.elements import ColumnElement + from sqlalchemy.sql.elements import TextClause + from sqlalchemy.sql.schema import CheckConstraint + from sqlalchemy.sql.schema import ForeignKey + from sqlalchemy.sql.schema import ForeignKeyConstraint + from sqlalchemy.sql.schema import MetaData + from sqlalchemy.sql.schema import PrimaryKeyConstraint + from sqlalchemy.sql.schema import Table + from sqlalchemy.sql.schema import UniqueConstraint + from sqlalchemy.sql.type_api import TypeEngine + + from ..runtime.migration import MigrationContext + + +class SchemaObjects: + def __init__( + self, migration_context: Optional[MigrationContext] = None + ) -> None: + self.migration_context = migration_context + + def primary_key_constraint( + self, + name: Optional[sqla_compat._ConstraintNameDefined], + table_name: str, + cols: Sequence[str], + schema: Optional[str] = None, + **dialect_kw, + ) -> PrimaryKeyConstraint: + m = self.metadata() + columns = [sa_schema.Column(n, NULLTYPE) for n in cols] + t = sa_schema.Table(table_name, m, *columns, schema=schema) + # SQLAlchemy primary key constraint name arg is wrongly typed on + # the SQLAlchemy side through 2.0.5 at least + p = sa_schema.PrimaryKeyConstraint( + *[t.c[n] for n in cols], name=name, **dialect_kw # type: ignore + ) + return p + + def foreign_key_constraint( + self, + name: Optional[sqla_compat._ConstraintNameDefined], + source: str, + referent: str, + local_cols: List[str], + remote_cols: List[str], + onupdate: Optional[str] = None, + ondelete: Optional[str] = None, + deferrable: Optional[bool] = None, + source_schema: Optional[str] = None, + referent_schema: Optional[str] = None, + initially: Optional[str] = None, + match: Optional[str] = None, + **dialect_kw, + ) -> ForeignKeyConstraint: + m = self.metadata() + if source == referent and source_schema == referent_schema: + t1_cols = local_cols + remote_cols + else: + t1_cols = local_cols + sa_schema.Table( + referent, + m, + *[sa_schema.Column(n, NULLTYPE) for n in remote_cols], + schema=referent_schema, + ) + + t1 = sa_schema.Table( + source, + m, + *[ + sa_schema.Column(n, NULLTYPE) + for n in util.unique_list(t1_cols) + ], + schema=source_schema, + ) + + tname = ( + "%s.%s" % (referent_schema, referent) + if referent_schema + else referent + ) + + dialect_kw["match"] = match + + f = sa_schema.ForeignKeyConstraint( + local_cols, + ["%s.%s" % (tname, n) for n in remote_cols], + name=name, + onupdate=onupdate, + ondelete=ondelete, + deferrable=deferrable, + initially=initially, + **dialect_kw, + ) + t1.append_constraint(f) + + return f + + def unique_constraint( + self, + name: Optional[sqla_compat._ConstraintNameDefined], + source: str, + local_cols: Sequence[str], + schema: Optional[str] = None, + **kw, + ) -> UniqueConstraint: + t = sa_schema.Table( + source, + self.metadata(), + *[sa_schema.Column(n, NULLTYPE) for n in local_cols], + schema=schema, + ) + kw["name"] = name + uq = sa_schema.UniqueConstraint(*[t.c[n] for n in local_cols], **kw) + # TODO: need event tests to ensure the event + # is fired off here + t.append_constraint(uq) + return uq + + def check_constraint( + self, + name: Optional[sqla_compat._ConstraintNameDefined], + source: str, + condition: Union[str, TextClause, ColumnElement[Any]], + schema: Optional[str] = None, + **kw, + ) -> Union[CheckConstraint]: + t = sa_schema.Table( + source, + self.metadata(), + sa_schema.Column("x", Integer), + schema=schema, + ) + ck = sa_schema.CheckConstraint(condition, name=name, **kw) + t.append_constraint(ck) + return ck + + def generic_constraint( + self, + name: Optional[sqla_compat._ConstraintNameDefined], + table_name: str, + type_: Optional[str], + schema: Optional[str] = None, + **kw, + ) -> Any: + t = self.table(table_name, schema=schema) + types: Dict[Optional[str], Any] = { + "foreignkey": lambda name: sa_schema.ForeignKeyConstraint( + [], [], name=name + ), + "primary": sa_schema.PrimaryKeyConstraint, + "unique": sa_schema.UniqueConstraint, + "check": lambda name: sa_schema.CheckConstraint("", name=name), + None: sa_schema.Constraint, + } + try: + const = types[type_] + except KeyError as ke: + raise TypeError( + "'type' can be one of %s" + % ", ".join(sorted(repr(x) for x in types)) + ) from ke + else: + const = const(name=name) + t.append_constraint(const) + return const + + def metadata(self) -> MetaData: + kw = {} + if ( + self.migration_context is not None + and "target_metadata" in self.migration_context.opts + ): + mt = self.migration_context.opts["target_metadata"] + if hasattr(mt, "naming_convention"): + kw["naming_convention"] = mt.naming_convention + return sa_schema.MetaData(**kw) + + def table(self, name: str, *columns, **kw) -> Table: + m = self.metadata() + + cols = [ + sqla_compat._copy(c) if c.table is not None else c + for c in columns + if isinstance(c, Column) + ] + # these flags have already added their UniqueConstraint / + # Index objects to the table, so flip them off here. + # SQLAlchemy tometadata() avoids this instead by preserving the + # flags and skipping the constraints that have _type_bound on them, + # but for a migration we'd rather list out the constraints + # explicitly. + _constraints_included = kw.pop("_constraints_included", False) + if _constraints_included: + for c in cols: + c.unique = c.index = False + + t = sa_schema.Table(name, m, *cols, **kw) + + constraints = [ + sqla_compat._copy(elem, target_table=t) + if getattr(elem, "parent", None) is not t + and getattr(elem, "parent", None) is not None + else elem + for elem in columns + if isinstance(elem, (Constraint, Index)) + ] + + for const in constraints: + t.append_constraint(const) + + for f in t.foreign_keys: + self._ensure_table_for_fk(m, f) + return t + + def column(self, name: str, type_: TypeEngine, **kw) -> Column: + return sa_schema.Column(name, type_, **kw) + + def index( + self, + name: Optional[str], + tablename: Optional[str], + columns: Sequence[Union[str, TextClause, ColumnElement[Any]]], + schema: Optional[str] = None, + **kw, + ) -> Index: + t = sa_schema.Table( + tablename or "no_table", + self.metadata(), + schema=schema, + ) + kw["_table"] = t + idx = sa_schema.Index( + name, + *[util.sqla_compat._textual_index_column(t, n) for n in columns], + **kw, + ) + return idx + + def _parse_table_key(self, table_key: str) -> Tuple[Optional[str], str]: + if "." in table_key: + tokens = table_key.split(".") + sname: Optional[str] = ".".join(tokens[0:-1]) + tname = tokens[-1] + else: + tname = table_key + sname = None + return (sname, tname) + + def _ensure_table_for_fk(self, metadata: MetaData, fk: ForeignKey) -> None: + """create a placeholder Table object for the referent of a + ForeignKey. + + """ + if isinstance(fk._colspec, str): + table_key, cname = fk._colspec.rsplit(".", 1) + sname, tname = self._parse_table_key(table_key) + if table_key not in metadata.tables: + rel_t = sa_schema.Table(tname, metadata, schema=sname) + else: + rel_t = metadata.tables[table_key] + if cname not in rel_t.c: + rel_t.append_column(sa_schema.Column(cname, NULLTYPE)) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/toimpl.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/toimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..4759f7fd2aa7d118ba0e811d5cb207e8b28d173a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/operations/toimpl.py @@ -0,0 +1,226 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from typing import TYPE_CHECKING + +from sqlalchemy import schema as sa_schema + +from . import ops +from .base import Operations +from ..util.sqla_compat import _copy +from ..util.sqla_compat import sqla_14 + +if TYPE_CHECKING: + from sqlalchemy.sql.schema import Table + + +@Operations.implementation_for(ops.AlterColumnOp) +def alter_column( + operations: "Operations", operation: "ops.AlterColumnOp" +) -> None: + compiler = operations.impl.dialect.statement_compiler( + operations.impl.dialect, None + ) + + existing_type = operation.existing_type + existing_nullable = operation.existing_nullable + existing_server_default = operation.existing_server_default + type_ = operation.modify_type + column_name = operation.column_name + table_name = operation.table_name + schema = operation.schema + server_default = operation.modify_server_default + new_column_name = operation.modify_name + nullable = operation.modify_nullable + comment = operation.modify_comment + existing_comment = operation.existing_comment + + def _count_constraint(constraint): + return not isinstance(constraint, sa_schema.PrimaryKeyConstraint) and ( + not constraint._create_rule or constraint._create_rule(compiler) + ) + + if existing_type and type_: + t = operations.schema_obj.table( + table_name, + sa_schema.Column(column_name, existing_type), + schema=schema, + ) + for constraint in t.constraints: + if _count_constraint(constraint): + operations.impl.drop_constraint(constraint) + + operations.impl.alter_column( + table_name, + column_name, + nullable=nullable, + server_default=server_default, + name=new_column_name, + type_=type_, + schema=schema, + existing_type=existing_type, + existing_server_default=existing_server_default, + existing_nullable=existing_nullable, + comment=comment, + existing_comment=existing_comment, + **operation.kw, + ) + + if type_: + t = operations.schema_obj.table( + table_name, + operations.schema_obj.column(column_name, type_), + schema=schema, + ) + for constraint in t.constraints: + if _count_constraint(constraint): + operations.impl.add_constraint(constraint) + + +@Operations.implementation_for(ops.DropTableOp) +def drop_table(operations: "Operations", operation: "ops.DropTableOp") -> None: + operations.impl.drop_table( + operation.to_table(operations.migration_context) + ) + + +@Operations.implementation_for(ops.DropColumnOp) +def drop_column( + operations: "Operations", operation: "ops.DropColumnOp" +) -> None: + column = operation.to_column(operations.migration_context) + operations.impl.drop_column( + operation.table_name, column, schema=operation.schema, **operation.kw + ) + + +@Operations.implementation_for(ops.CreateIndexOp) +def create_index( + operations: "Operations", operation: "ops.CreateIndexOp" +) -> None: + idx = operation.to_index(operations.migration_context) + kw = {} + if operation.if_not_exists is not None: + if not sqla_14: + raise NotImplementedError("SQLAlchemy 1.4+ required") + + kw["if_not_exists"] = operation.if_not_exists + operations.impl.create_index(idx, **kw) + + +@Operations.implementation_for(ops.DropIndexOp) +def drop_index(operations: "Operations", operation: "ops.DropIndexOp") -> None: + kw = {} + if operation.if_exists is not None: + if not sqla_14: + raise NotImplementedError("SQLAlchemy 1.4+ required") + + kw["if_exists"] = operation.if_exists + + operations.impl.drop_index( + operation.to_index(operations.migration_context), + **kw, + ) + + +@Operations.implementation_for(ops.CreateTableOp) +def create_table( + operations: "Operations", operation: "ops.CreateTableOp" +) -> "Table": + table = operation.to_table(operations.migration_context) + operations.impl.create_table(table) + return table + + +@Operations.implementation_for(ops.RenameTableOp) +def rename_table( + operations: "Operations", operation: "ops.RenameTableOp" +) -> None: + operations.impl.rename_table( + operation.table_name, operation.new_table_name, schema=operation.schema + ) + + +@Operations.implementation_for(ops.CreateTableCommentOp) +def create_table_comment( + operations: "Operations", operation: "ops.CreateTableCommentOp" +) -> None: + table = operation.to_table(operations.migration_context) + operations.impl.create_table_comment(table) + + +@Operations.implementation_for(ops.DropTableCommentOp) +def drop_table_comment( + operations: "Operations", operation: "ops.DropTableCommentOp" +) -> None: + table = operation.to_table(operations.migration_context) + operations.impl.drop_table_comment(table) + + +@Operations.implementation_for(ops.AddColumnOp) +def add_column(operations: "Operations", operation: "ops.AddColumnOp") -> None: + table_name = operation.table_name + column = operation.column + schema = operation.schema + kw = operation.kw + + if column.table is not None: + column = _copy(column) + + t = operations.schema_obj.table(table_name, column, schema=schema) + operations.impl.add_column(table_name, column, schema=schema, **kw) + + for constraint in t.constraints: + if not isinstance(constraint, sa_schema.PrimaryKeyConstraint): + operations.impl.add_constraint(constraint) + for index in t.indexes: + operations.impl.create_index(index) + + with_comment = ( + operations.impl.dialect.supports_comments + and not operations.impl.dialect.inline_comments + ) + comment = column.comment + if comment and with_comment: + operations.impl.create_column_comment(column) + + +@Operations.implementation_for(ops.AddConstraintOp) +def create_constraint( + operations: "Operations", operation: "ops.AddConstraintOp" +) -> None: + operations.impl.add_constraint( + operation.to_constraint(operations.migration_context) + ) + + +@Operations.implementation_for(ops.DropConstraintOp) +def drop_constraint( + operations: "Operations", operation: "ops.DropConstraintOp" +) -> None: + operations.impl.drop_constraint( + operations.schema_obj.generic_constraint( + operation.constraint_name, + operation.table_name, + operation.constraint_type, + schema=operation.schema, + ) + ) + + +@Operations.implementation_for(ops.BulkInsertOp) +def bulk_insert( + operations: "Operations", operation: "ops.BulkInsertOp" +) -> None: + operations.impl.bulk_insert( # type: ignore[union-attr] + operation.table, operation.rows, multiinsert=operation.multiinsert + ) + + +@Operations.implementation_for(ops.ExecuteSQLOp) +def execute_sql( + operations: "Operations", operation: "ops.ExecuteSQLOp" +) -> None: + operations.migration_context.impl.execute( + operation.sqltext, execution_options=operation.execution_options + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/runtime/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/runtime/environment.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/runtime/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..d64b2adc279761b40724b2c7c7c7f53da1e77019 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/runtime/environment.py @@ -0,0 +1,1053 @@ +from __future__ import annotations + +from typing import Any +from typing import Callable +from typing import Collection +from typing import ContextManager +from typing import Dict +from typing import List +from typing import Mapping +from typing import MutableMapping +from typing import Optional +from typing import overload +from typing import Sequence +from typing import TextIO +from typing import Tuple +from typing import TYPE_CHECKING +from typing import Union + +from sqlalchemy.sql.schema import Column +from sqlalchemy.sql.schema import FetchedValue +from typing_extensions import Literal + +from .migration import _ProxyTransaction +from .migration import MigrationContext +from .. import util +from ..operations import Operations +from ..script.revision import _GetRevArg + +if TYPE_CHECKING: + from sqlalchemy.engine import URL + from sqlalchemy.engine.base import Connection + from sqlalchemy.sql import Executable + from sqlalchemy.sql.schema import MetaData + from sqlalchemy.sql.schema import SchemaItem + from sqlalchemy.sql.type_api import TypeEngine + + from .migration import MigrationInfo + from ..autogenerate.api import AutogenContext + from ..config import Config + from ..ddl import DefaultImpl + from ..operations.ops import MigrationScript + from ..script.base import ScriptDirectory + +_RevNumber = Optional[Union[str, Tuple[str, ...]]] + +ProcessRevisionDirectiveFn = Callable[ + [MigrationContext, _GetRevArg, List["MigrationScript"]], None +] + +RenderItemFn = Callable[ + [str, Any, "AutogenContext"], Union[str, Literal[False]] +] + +NameFilterType = Literal[ + "schema", + "table", + "column", + "index", + "unique_constraint", + "foreign_key_constraint", +] +NameFilterParentNames = MutableMapping[ + Literal["schema_name", "table_name", "schema_qualified_table_name"], + Optional[str], +] +IncludeNameFn = Callable[ + [Optional[str], NameFilterType, NameFilterParentNames], bool +] + +IncludeObjectFn = Callable[ + [ + "SchemaItem", + Optional[str], + NameFilterType, + bool, + Optional["SchemaItem"], + ], + bool, +] + +OnVersionApplyFn = Callable[ + [MigrationContext, "MigrationInfo", Collection[Any], Mapping[str, Any]], + None, +] + +CompareServerDefault = Callable[ + [ + MigrationContext, + "Column[Any]", + "Column[Any]", + Optional[str], + Optional[FetchedValue], + Optional[str], + ], + Optional[bool], +] + +CompareType = Callable[ + [ + MigrationContext, + "Column[Any]", + "Column[Any]", + "TypeEngine[Any]", + "TypeEngine[Any]", + ], + Optional[bool], +] + + +class EnvironmentContext(util.ModuleClsProxy): + + """A configurational facade made available in an ``env.py`` script. + + The :class:`.EnvironmentContext` acts as a *facade* to the more + nuts-and-bolts objects of :class:`.MigrationContext` as well as certain + aspects of :class:`.Config`, + within the context of the ``env.py`` script that is invoked by + most Alembic commands. + + :class:`.EnvironmentContext` is normally instantiated + when a command in :mod:`alembic.command` is run. It then makes + itself available in the ``alembic.context`` module for the scope + of the command. From within an ``env.py`` script, the current + :class:`.EnvironmentContext` is available by importing this module. + + :class:`.EnvironmentContext` also supports programmatic usage. + At this level, it acts as a Python context manager, that is, is + intended to be used using the + ``with:`` statement. A typical use of :class:`.EnvironmentContext`:: + + from alembic.config import Config + from alembic.script import ScriptDirectory + + config = Config() + config.set_main_option("script_location", "myapp:migrations") + script = ScriptDirectory.from_config(config) + + + def my_function(rev, context): + '''do something with revision "rev", which + will be the current database revision, + and "context", which is the MigrationContext + that the env.py will create''' + + + with EnvironmentContext( + config, + script, + fn=my_function, + as_sql=False, + starting_rev="base", + destination_rev="head", + tag="sometag", + ): + script.run_env() + + The above script will invoke the ``env.py`` script + within the migration environment. If and when ``env.py`` + calls :meth:`.MigrationContext.run_migrations`, the + ``my_function()`` function above will be called + by the :class:`.MigrationContext`, given the context + itself as well as the current revision in the database. + + .. note:: + + For most API usages other than full blown + invocation of migration scripts, the :class:`.MigrationContext` + and :class:`.ScriptDirectory` objects can be created and + used directly. The :class:`.EnvironmentContext` object + is *only* needed when you need to actually invoke the + ``env.py`` module present in the migration environment. + + """ + + _migration_context: Optional[MigrationContext] = None + + config: Config = None # type:ignore[assignment] + """An instance of :class:`.Config` representing the + configuration file contents as well as other variables + set programmatically within it.""" + + script: ScriptDirectory = None # type:ignore[assignment] + """An instance of :class:`.ScriptDirectory` which provides + programmatic access to version files within the ``versions/`` + directory. + + """ + + def __init__( + self, config: Config, script: ScriptDirectory, **kw: Any + ) -> None: + r"""Construct a new :class:`.EnvironmentContext`. + + :param config: a :class:`.Config` instance. + :param script: a :class:`.ScriptDirectory` instance. + :param \**kw: keyword options that will be ultimately + passed along to the :class:`.MigrationContext` when + :meth:`.EnvironmentContext.configure` is called. + + """ + self.config = config + self.script = script + self.context_opts = kw + + def __enter__(self) -> EnvironmentContext: + """Establish a context which provides a + :class:`.EnvironmentContext` object to + env.py scripts. + + The :class:`.EnvironmentContext` will + be made available as ``from alembic import context``. + + """ + self._install_proxy() + return self + + def __exit__(self, *arg: Any, **kw: Any) -> None: + self._remove_proxy() + + def is_offline_mode(self) -> bool: + """Return True if the current migrations environment + is running in "offline mode". + + This is ``True`` or ``False`` depending + on the ``--sql`` flag passed. + + This function does not require that the :class:`.MigrationContext` + has been configured. + + """ + return self.context_opts.get("as_sql", False) # type: ignore[no-any-return] # noqa: E501 + + def is_transactional_ddl(self) -> bool: + """Return True if the context is configured to expect a + transactional DDL capable backend. + + This defaults to the type of database in use, and + can be overridden by the ``transactional_ddl`` argument + to :meth:`.configure` + + This function requires that a :class:`.MigrationContext` + has first been made available via :meth:`.configure`. + + """ + return self.get_context().impl.transactional_ddl + + def requires_connection(self) -> bool: + return not self.is_offline_mode() + + def get_head_revision(self) -> _RevNumber: + """Return the hex identifier of the 'head' script revision. + + If the script directory has multiple heads, this + method raises a :class:`.CommandError`; + :meth:`.EnvironmentContext.get_head_revisions` should be preferred. + + This function does not require that the :class:`.MigrationContext` + has been configured. + + .. seealso:: :meth:`.EnvironmentContext.get_head_revisions` + + """ + return self.script.as_revision_number("head") + + def get_head_revisions(self) -> _RevNumber: + """Return the hex identifier of the 'heads' script revision(s). + + This returns a tuple containing the version number of all + heads in the script directory. + + This function does not require that the :class:`.MigrationContext` + has been configured. + + """ + return self.script.as_revision_number("heads") + + def get_starting_revision_argument(self) -> _RevNumber: + """Return the 'starting revision' argument, + if the revision was passed using ``start:end``. + + This is only meaningful in "offline" mode. + Returns ``None`` if no value is available + or was configured. + + This function does not require that the :class:`.MigrationContext` + has been configured. + + """ + if self._migration_context is not None: + return self.script.as_revision_number( + self.get_context()._start_from_rev + ) + elif "starting_rev" in self.context_opts: + return self.script.as_revision_number( + self.context_opts["starting_rev"] + ) + else: + # this should raise only in the case that a command + # is being run where the "starting rev" is never applicable; + # this is to catch scripts which rely upon this in + # non-sql mode or similar + raise util.CommandError( + "No starting revision argument is available." + ) + + def get_revision_argument(self) -> _RevNumber: + """Get the 'destination' revision argument. + + This is typically the argument passed to the + ``upgrade`` or ``downgrade`` command. + + If it was specified as ``head``, the actual + version number is returned; if specified + as ``base``, ``None`` is returned. + + This function does not require that the :class:`.MigrationContext` + has been configured. + + """ + return self.script.as_revision_number( + self.context_opts["destination_rev"] + ) + + def get_tag_argument(self) -> Optional[str]: + """Return the value passed for the ``--tag`` argument, if any. + + The ``--tag`` argument is not used directly by Alembic, + but is available for custom ``env.py`` configurations that + wish to use it; particularly for offline generation scripts + that wish to generate tagged filenames. + + This function does not require that the :class:`.MigrationContext` + has been configured. + + .. seealso:: + + :meth:`.EnvironmentContext.get_x_argument` - a newer and more + open ended system of extending ``env.py`` scripts via the command + line. + + """ + return self.context_opts.get("tag", None) # type: ignore[no-any-return] # noqa: E501 + + @overload + def get_x_argument(self, as_dictionary: Literal[False]) -> List[str]: + ... + + @overload + def get_x_argument(self, as_dictionary: Literal[True]) -> Dict[str, str]: + ... + + @overload + def get_x_argument( + self, as_dictionary: bool = ... + ) -> Union[List[str], Dict[str, str]]: + ... + + def get_x_argument( + self, as_dictionary: bool = False + ) -> Union[List[str], Dict[str, str]]: + """Return the value(s) passed for the ``-x`` argument, if any. + + The ``-x`` argument is an open ended flag that allows any user-defined + value or values to be passed on the command line, then available + here for consumption by a custom ``env.py`` script. + + The return value is a list, returned directly from the ``argparse`` + structure. If ``as_dictionary=True`` is passed, the ``x`` arguments + are parsed using ``key=value`` format into a dictionary that is + then returned. If there is no ``=`` in the argument, value is an empty + string. + + .. versionchanged:: 1.13.1 Support ``as_dictionary=True`` when + arguments are passed without the ``=`` symbol. + + For example, to support passing a database URL on the command line, + the standard ``env.py`` script can be modified like this:: + + cmd_line_url = context.get_x_argument( + as_dictionary=True).get('dbname') + if cmd_line_url: + engine = create_engine(cmd_line_url) + else: + engine = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool) + + This then takes effect by running the ``alembic`` script as:: + + alembic -x dbname=postgresql://user:pass@host/dbname upgrade head + + This function does not require that the :class:`.MigrationContext` + has been configured. + + .. seealso:: + + :meth:`.EnvironmentContext.get_tag_argument` + + :attr:`.Config.cmd_opts` + + """ + if self.config.cmd_opts is not None: + value = self.config.cmd_opts.x or [] + else: + value = [] + if as_dictionary: + dict_value = {} + for arg in value: + x_key, _, x_value = arg.partition("=") + dict_value[x_key] = x_value + value = dict_value + + return value + + def configure( + self, + connection: Optional[Connection] = None, + url: Optional[Union[str, URL]] = None, + dialect_name: Optional[str] = None, + dialect_opts: Optional[Dict[str, Any]] = None, + transactional_ddl: Optional[bool] = None, + transaction_per_migration: bool = False, + output_buffer: Optional[TextIO] = None, + starting_rev: Optional[str] = None, + tag: Optional[str] = None, + template_args: Optional[Dict[str, Any]] = None, + render_as_batch: bool = False, + target_metadata: Union[MetaData, Sequence[MetaData], None] = None, + include_name: Optional[IncludeNameFn] = None, + include_object: Optional[IncludeObjectFn] = None, + include_schemas: bool = False, + process_revision_directives: Optional[ + ProcessRevisionDirectiveFn + ] = None, + compare_type: Union[bool, CompareType] = True, + compare_server_default: Union[bool, CompareServerDefault] = False, + render_item: Optional[RenderItemFn] = None, + literal_binds: bool = False, + upgrade_token: str = "upgrades", + downgrade_token: str = "downgrades", + alembic_module_prefix: str = "op.", + sqlalchemy_module_prefix: str = "sa.", + user_module_prefix: Optional[str] = None, + on_version_apply: Optional[OnVersionApplyFn] = None, + **kw: Any, + ) -> None: + """Configure a :class:`.MigrationContext` within this + :class:`.EnvironmentContext` which will provide database + connectivity and other configuration to a series of + migration scripts. + + Many methods on :class:`.EnvironmentContext` require that + this method has been called in order to function, as they + ultimately need to have database access or at least access + to the dialect in use. Those which do are documented as such. + + The important thing needed by :meth:`.configure` is a + means to determine what kind of database dialect is in use. + An actual connection to that database is needed only if + the :class:`.MigrationContext` is to be used in + "online" mode. + + If the :meth:`.is_offline_mode` function returns ``True``, + then no connection is needed here. Otherwise, the + ``connection`` parameter should be present as an + instance of :class:`sqlalchemy.engine.Connection`. + + This function is typically called from the ``env.py`` + script within a migration environment. It can be called + multiple times for an invocation. The most recent + :class:`~sqlalchemy.engine.Connection` + for which it was called is the one that will be operated upon + by the next call to :meth:`.run_migrations`. + + General parameters: + + :param connection: a :class:`~sqlalchemy.engine.Connection` + to use + for SQL execution in "online" mode. When present, is also + used to determine the type of dialect in use. + :param url: a string database url, or a + :class:`sqlalchemy.engine.url.URL` object. + The type of dialect to be used will be derived from this if + ``connection`` is not passed. + :param dialect_name: string name of a dialect, such as + "postgresql", "mssql", etc. + The type of dialect to be used will be derived from this if + ``connection`` and ``url`` are not passed. + :param dialect_opts: dictionary of options to be passed to dialect + constructor. + :param transactional_ddl: Force the usage of "transactional" + DDL on or off; + this otherwise defaults to whether or not the dialect in + use supports it. + :param transaction_per_migration: if True, nest each migration script + in a transaction rather than the full series of migrations to + run. + :param output_buffer: a file-like object that will be used + for textual output + when the ``--sql`` option is used to generate SQL scripts. + Defaults to + ``sys.stdout`` if not passed here and also not present on + the :class:`.Config` + object. The value here overrides that of the :class:`.Config` + object. + :param output_encoding: when using ``--sql`` to generate SQL + scripts, apply this encoding to the string output. + :param literal_binds: when using ``--sql`` to generate SQL + scripts, pass through the ``literal_binds`` flag to the compiler + so that any literal values that would ordinarily be bound + parameters are converted to plain strings. + + .. warning:: Dialects can typically only handle simple datatypes + like strings and numbers for auto-literal generation. Datatypes + like dates, intervals, and others may still require manual + formatting, typically using :meth:`.Operations.inline_literal`. + + .. note:: the ``literal_binds`` flag is ignored on SQLAlchemy + versions prior to 0.8 where this feature is not supported. + + .. seealso:: + + :meth:`.Operations.inline_literal` + + :param starting_rev: Override the "starting revision" argument + when using ``--sql`` mode. + :param tag: a string tag for usage by custom ``env.py`` scripts. + Set via the ``--tag`` option, can be overridden here. + :param template_args: dictionary of template arguments which + will be added to the template argument environment when + running the "revision" command. Note that the script environment + is only run within the "revision" command if the --autogenerate + option is used, or if the option "revision_environment=true" + is present in the alembic.ini file. + + :param version_table: The name of the Alembic version table. + The default is ``'alembic_version'``. + :param version_table_schema: Optional schema to place version + table within. + :param version_table_pk: boolean, whether the Alembic version table + should use a primary key constraint for the "value" column; this + only takes effect when the table is first created. + Defaults to True; setting to False should not be necessary and is + here for backwards compatibility reasons. + :param on_version_apply: a callable or collection of callables to be + run for each migration step. + The callables will be run in the order they are given, once for + each migration step, after the respective operation has been + applied but before its transaction is finalized. + Each callable accepts no positional arguments and the following + keyword arguments: + + * ``ctx``: the :class:`.MigrationContext` running the migration, + * ``step``: a :class:`.MigrationInfo` representing the + step currently being applied, + * ``heads``: a collection of version strings representing the + current heads, + * ``run_args``: the ``**kwargs`` passed to :meth:`.run_migrations`. + + Parameters specific to the autogenerate feature, when + ``alembic revision`` is run with the ``--autogenerate`` feature: + + :param target_metadata: a :class:`sqlalchemy.schema.MetaData` + object, or a sequence of :class:`~sqlalchemy.schema.MetaData` + objects, that will be consulted during autogeneration. + The tables present in each :class:`~sqlalchemy.schema.MetaData` + will be compared against + what is locally available on the target + :class:`~sqlalchemy.engine.Connection` + to produce candidate upgrade/downgrade operations. + :param compare_type: Indicates type comparison behavior during + an autogenerate + operation. Defaults to ``True`` turning on type comparison, which + has good accuracy on most backends. See :ref:`compare_types` + for an example as well as information on other type + comparison options. Set to ``False`` which disables type + comparison. A callable can also be passed to provide custom type + comparison, see :ref:`compare_types` for additional details. + + .. versionchanged:: 1.12.0 The default value of + :paramref:`.EnvironmentContext.configure.compare_type` has been + changed to ``True``. + + .. seealso:: + + :ref:`compare_types` + + :paramref:`.EnvironmentContext.configure.compare_server_default` + + :param compare_server_default: Indicates server default comparison + behavior during + an autogenerate operation. Defaults to ``False`` which disables + server default + comparison. Set to ``True`` to turn on server default comparison, + which has + varied accuracy depending on backend. + + To customize server default comparison behavior, a callable may + be specified + which can filter server default comparisons during an + autogenerate operation. + defaults during an autogenerate operation. The format of this + callable is:: + + def my_compare_server_default(context, inspected_column, + metadata_column, inspected_default, metadata_default, + rendered_metadata_default): + # return True if the defaults are different, + # False if not, or None to allow the default implementation + # to compare these defaults + return None + + context.configure( + # ... + compare_server_default = my_compare_server_default + ) + + ``inspected_column`` is a dictionary structure as returned by + :meth:`sqlalchemy.engine.reflection.Inspector.get_columns`, whereas + ``metadata_column`` is a :class:`sqlalchemy.schema.Column` from + the local model environment. + + A return value of ``None`` indicates to allow default server default + comparison + to proceed. Note that some backends such as Postgresql actually + execute + the two defaults on the database side to compare for equivalence. + + .. seealso:: + + :paramref:`.EnvironmentContext.configure.compare_type` + + :param include_name: A callable function which is given + the chance to return ``True`` or ``False`` for any database reflected + object based on its name, including database schema names when + the :paramref:`.EnvironmentContext.configure.include_schemas` flag + is set to ``True``. + + The function accepts the following positional arguments: + + * ``name``: the name of the object, such as schema name or table name. + Will be ``None`` when indicating the default schema name of the + database connection. + * ``type``: a string describing the type of object; currently + ``"schema"``, ``"table"``, ``"column"``, ``"index"``, + ``"unique_constraint"``, or ``"foreign_key_constraint"`` + * ``parent_names``: a dictionary of "parent" object names, that are + relative to the name being given. Keys in this dictionary may + include: ``"schema_name"``, ``"table_name"`` or + ``"schema_qualified_table_name"``. + + E.g.:: + + def include_name(name, type_, parent_names): + if type_ == "schema": + return name in ["schema_one", "schema_two"] + else: + return True + + context.configure( + # ... + include_schemas = True, + include_name = include_name + ) + + .. seealso:: + + :ref:`autogenerate_include_hooks` + + :paramref:`.EnvironmentContext.configure.include_object` + + :paramref:`.EnvironmentContext.configure.include_schemas` + + + :param include_object: A callable function which is given + the chance to return ``True`` or ``False`` for any object, + indicating if the given object should be considered in the + autogenerate sweep. + + The function accepts the following positional arguments: + + * ``object``: a :class:`~sqlalchemy.schema.SchemaItem` object such + as a :class:`~sqlalchemy.schema.Table`, + :class:`~sqlalchemy.schema.Column`, + :class:`~sqlalchemy.schema.Index` + :class:`~sqlalchemy.schema.UniqueConstraint`, + or :class:`~sqlalchemy.schema.ForeignKeyConstraint` object + * ``name``: the name of the object. This is typically available + via ``object.name``. + * ``type``: a string describing the type of object; currently + ``"table"``, ``"column"``, ``"index"``, ``"unique_constraint"``, + or ``"foreign_key_constraint"`` + * ``reflected``: ``True`` if the given object was produced based on + table reflection, ``False`` if it's from a local :class:`.MetaData` + object. + * ``compare_to``: the object being compared against, if available, + else ``None``. + + E.g.:: + + def include_object(object, name, type_, reflected, compare_to): + if (type_ == "column" and + not reflected and + object.info.get("skip_autogenerate", False)): + return False + else: + return True + + context.configure( + # ... + include_object = include_object + ) + + For the use case of omitting specific schemas from a target database + when :paramref:`.EnvironmentContext.configure.include_schemas` is + set to ``True``, the :attr:`~sqlalchemy.schema.Table.schema` + attribute can be checked for each :class:`~sqlalchemy.schema.Table` + object passed to the hook, however it is much more efficient + to filter on schemas before reflection of objects takes place + using the :paramref:`.EnvironmentContext.configure.include_name` + hook. + + .. seealso:: + + :ref:`autogenerate_include_hooks` + + :paramref:`.EnvironmentContext.configure.include_name` + + :paramref:`.EnvironmentContext.configure.include_schemas` + + :param render_as_batch: if True, commands which alter elements + within a table will be placed under a ``with batch_alter_table():`` + directive, so that batch migrations will take place. + + .. seealso:: + + :ref:`batch_migrations` + + :param include_schemas: If True, autogenerate will scan across + all schemas located by the SQLAlchemy + :meth:`~sqlalchemy.engine.reflection.Inspector.get_schema_names` + method, and include all differences in tables found across all + those schemas. When using this option, you may want to also + use the :paramref:`.EnvironmentContext.configure.include_name` + parameter to specify a callable which + can filter the tables/schemas that get included. + + .. seealso:: + + :ref:`autogenerate_include_hooks` + + :paramref:`.EnvironmentContext.configure.include_name` + + :paramref:`.EnvironmentContext.configure.include_object` + + :param render_item: Callable that can be used to override how + any schema item, i.e. column, constraint, type, + etc., is rendered for autogenerate. The callable receives a + string describing the type of object, the object, and + the autogen context. If it returns False, the + default rendering method will be used. If it returns None, + the item will not be rendered in the context of a Table + construct, that is, can be used to skip columns or constraints + within op.create_table():: + + def my_render_column(type_, col, autogen_context): + if type_ == "column" and isinstance(col, MySpecialCol): + return repr(col) + else: + return False + + context.configure( + # ... + render_item = my_render_column + ) + + Available values for the type string include: ``"column"``, + ``"primary_key"``, ``"foreign_key"``, ``"unique"``, ``"check"``, + ``"type"``, ``"server_default"``. + + .. seealso:: + + :ref:`autogen_render_types` + + :param upgrade_token: When autogenerate completes, the text of the + candidate upgrade operations will be present in this template + variable when ``script.py.mako`` is rendered. Defaults to + ``upgrades``. + :param downgrade_token: When autogenerate completes, the text of the + candidate downgrade operations will be present in this + template variable when ``script.py.mako`` is rendered. Defaults to + ``downgrades``. + + :param alembic_module_prefix: When autogenerate refers to Alembic + :mod:`alembic.operations` constructs, this prefix will be used + (i.e. ``op.create_table``) Defaults to "``op.``". + Can be ``None`` to indicate no prefix. + + :param sqlalchemy_module_prefix: When autogenerate refers to + SQLAlchemy + :class:`~sqlalchemy.schema.Column` or type classes, this prefix + will be used + (i.e. ``sa.Column("somename", sa.Integer)``) Defaults to "``sa.``". + Can be ``None`` to indicate no prefix. + Note that when dialect-specific types are rendered, autogenerate + will render them using the dialect module name, i.e. ``mssql.BIT()``, + ``postgresql.UUID()``. + + :param user_module_prefix: When autogenerate refers to a SQLAlchemy + type (e.g. :class:`.TypeEngine`) where the module name is not + under the ``sqlalchemy`` namespace, this prefix will be used + within autogenerate. If left at its default of + ``None``, the ``__module__`` attribute of the type is used to + render the import module. It's a good practice to set this + and to have all custom types be available from a fixed module space, + in order to future-proof migration files against reorganizations + in modules. + + .. seealso:: + + :ref:`autogen_module_prefix` + + :param process_revision_directives: a callable function that will + be passed a structure representing the end result of an autogenerate + or plain "revision" operation, which can be manipulated to affect + how the ``alembic revision`` command ultimately outputs new + revision scripts. The structure of the callable is:: + + def process_revision_directives(context, revision, directives): + pass + + The ``directives`` parameter is a Python list containing + a single :class:`.MigrationScript` directive, which represents + the revision file to be generated. This list as well as its + contents may be freely modified to produce any set of commands. + The section :ref:`customizing_revision` shows an example of + doing this. The ``context`` parameter is the + :class:`.MigrationContext` in use, + and ``revision`` is a tuple of revision identifiers representing the + current revision of the database. + + The callable is invoked at all times when the ``--autogenerate`` + option is passed to ``alembic revision``. If ``--autogenerate`` + is not passed, the callable is invoked only if the + ``revision_environment`` variable is set to True in the Alembic + configuration, in which case the given ``directives`` collection + will contain empty :class:`.UpgradeOps` and :class:`.DowngradeOps` + collections for ``.upgrade_ops`` and ``.downgrade_ops``. The + ``--autogenerate`` option itself can be inferred by inspecting + ``context.config.cmd_opts.autogenerate``. + + The callable function may optionally be an instance of + a :class:`.Rewriter` object. This is a helper object that + assists in the production of autogenerate-stream rewriter functions. + + .. seealso:: + + :ref:`customizing_revision` + + :ref:`autogen_rewriter` + + :paramref:`.command.revision.process_revision_directives` + + Parameters specific to individual backends: + + :param mssql_batch_separator: The "batch separator" which will + be placed between each statement when generating offline SQL Server + migrations. Defaults to ``GO``. Note this is in addition to the + customary semicolon ``;`` at the end of each statement; SQL Server + considers the "batch separator" to denote the end of an + individual statement execution, and cannot group certain + dependent operations in one step. + :param oracle_batch_separator: The "batch separator" which will + be placed between each statement when generating offline + Oracle migrations. Defaults to ``/``. Oracle doesn't add a + semicolon between statements like most other backends. + + """ + opts = self.context_opts + if transactional_ddl is not None: + opts["transactional_ddl"] = transactional_ddl + if output_buffer is not None: + opts["output_buffer"] = output_buffer + elif self.config.output_buffer is not None: + opts["output_buffer"] = self.config.output_buffer + if starting_rev: + opts["starting_rev"] = starting_rev + if tag: + opts["tag"] = tag + if template_args and "template_args" in opts: + opts["template_args"].update(template_args) + opts["transaction_per_migration"] = transaction_per_migration + opts["target_metadata"] = target_metadata + opts["include_name"] = include_name + opts["include_object"] = include_object + opts["include_schemas"] = include_schemas + opts["render_as_batch"] = render_as_batch + opts["upgrade_token"] = upgrade_token + opts["downgrade_token"] = downgrade_token + opts["sqlalchemy_module_prefix"] = sqlalchemy_module_prefix + opts["alembic_module_prefix"] = alembic_module_prefix + opts["user_module_prefix"] = user_module_prefix + opts["literal_binds"] = literal_binds + opts["process_revision_directives"] = process_revision_directives + opts["on_version_apply"] = util.to_tuple(on_version_apply, default=()) + + if render_item is not None: + opts["render_item"] = render_item + opts["compare_type"] = compare_type + if compare_server_default is not None: + opts["compare_server_default"] = compare_server_default + opts["script"] = self.script + + opts.update(kw) + + self._migration_context = MigrationContext.configure( + connection=connection, + url=url, + dialect_name=dialect_name, + environment_context=self, + dialect_opts=dialect_opts, + opts=opts, + ) + + def run_migrations(self, **kw: Any) -> None: + """Run migrations as determined by the current command line + configuration + as well as versioning information present (or not) in the current + database connection (if one is present). + + The function accepts optional ``**kw`` arguments. If these are + passed, they are sent directly to the ``upgrade()`` and + ``downgrade()`` + functions within each target revision file. By modifying the + ``script.py.mako`` file so that the ``upgrade()`` and ``downgrade()`` + functions accept arguments, parameters can be passed here so that + contextual information, usually information to identify a particular + database in use, can be passed from a custom ``env.py`` script + to the migration functions. + + This function requires that a :class:`.MigrationContext` has + first been made available via :meth:`.configure`. + + """ + assert self._migration_context is not None + with Operations.context(self._migration_context): + self.get_context().run_migrations(**kw) + + def execute( + self, + sql: Union[Executable, str], + execution_options: Optional[Dict[str, Any]] = None, + ) -> None: + """Execute the given SQL using the current change context. + + The behavior of :meth:`.execute` is the same + as that of :meth:`.Operations.execute`. Please see that + function's documentation for full detail including + caveats and limitations. + + This function requires that a :class:`.MigrationContext` has + first been made available via :meth:`.configure`. + + """ + self.get_context().execute(sql, execution_options=execution_options) + + def static_output(self, text: str) -> None: + """Emit text directly to the "offline" SQL stream. + + Typically this is for emitting comments that + start with --. The statement is not treated + as a SQL execution, no ; or batch separator + is added, etc. + + """ + self.get_context().impl.static_output(text) + + def begin_transaction( + self, + ) -> Union[_ProxyTransaction, ContextManager[None]]: + """Return a context manager that will + enclose an operation within a "transaction", + as defined by the environment's offline + and transactional DDL settings. + + e.g.:: + + with context.begin_transaction(): + context.run_migrations() + + :meth:`.begin_transaction` is intended to + "do the right thing" regardless of + calling context: + + * If :meth:`.is_transactional_ddl` is ``False``, + returns a "do nothing" context manager + which otherwise produces no transactional + state or directives. + * If :meth:`.is_offline_mode` is ``True``, + returns a context manager that will + invoke the :meth:`.DefaultImpl.emit_begin` + and :meth:`.DefaultImpl.emit_commit` + methods, which will produce the string + directives ``BEGIN`` and ``COMMIT`` on + the output stream, as rendered by the + target backend (e.g. SQL Server would + emit ``BEGIN TRANSACTION``). + * Otherwise, calls :meth:`sqlalchemy.engine.Connection.begin` + on the current online connection, which + returns a :class:`sqlalchemy.engine.Transaction` + object. This object demarcates a real + transaction and is itself a context manager, + which will roll back if an exception + is raised. + + Note that a custom ``env.py`` script which + has more specific transactional needs can of course + manipulate the :class:`~sqlalchemy.engine.Connection` + directly to produce transactional state in "online" + mode. + + """ + + return self.get_context().begin_transaction() + + def get_context(self) -> MigrationContext: + """Return the current :class:`.MigrationContext` object. + + If :meth:`.EnvironmentContext.configure` has not been + called yet, raises an exception. + + """ + + if self._migration_context is None: + raise Exception("No context has been configured yet.") + return self._migration_context + + def get_bind(self) -> Connection: + """Return the current 'bind'. + + In "online" mode, this is the + :class:`sqlalchemy.engine.Connection` currently being used + to emit SQL to the database. + + This function requires that a :class:`.MigrationContext` + has first been made available via :meth:`.configure`. + + """ + return self.get_context().bind # type: ignore[return-value] + + def get_impl(self) -> DefaultImpl: + return self.get_context().impl diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/runtime/migration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/runtime/migration.py new file mode 100644 index 0000000000000000000000000000000000000000..95c69bc692555e8614570691b0309b866bac2946 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/runtime/migration.py @@ -0,0 +1,1396 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +from contextlib import contextmanager +from contextlib import nullcontext +import logging +import sys +from typing import Any +from typing import Callable +from typing import cast +from typing import Collection +from typing import ContextManager +from typing import Dict +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Optional +from typing import Set +from typing import Tuple +from typing import TYPE_CHECKING +from typing import Union + +from sqlalchemy import Column +from sqlalchemy import literal_column +from sqlalchemy import MetaData +from sqlalchemy import PrimaryKeyConstraint +from sqlalchemy import String +from sqlalchemy import Table +from sqlalchemy.engine import Engine +from sqlalchemy.engine import url as sqla_url +from sqlalchemy.engine.strategies import MockEngineStrategy + +from .. import ddl +from .. import util +from ..util import sqla_compat +from ..util.compat import EncodedIO + +if TYPE_CHECKING: + from sqlalchemy.engine import Dialect + from sqlalchemy.engine import URL + from sqlalchemy.engine.base import Connection + from sqlalchemy.engine.base import Transaction + from sqlalchemy.engine.mock import MockConnection + from sqlalchemy.sql import Executable + + from .environment import EnvironmentContext + from ..config import Config + from ..script.base import Script + from ..script.base import ScriptDirectory + from ..script.revision import _RevisionOrBase + from ..script.revision import Revision + from ..script.revision import RevisionMap + +log = logging.getLogger(__name__) + + +class _ProxyTransaction: + def __init__(self, migration_context: MigrationContext) -> None: + self.migration_context = migration_context + + @property + def _proxied_transaction(self) -> Optional[Transaction]: + return self.migration_context._transaction + + def rollback(self) -> None: + t = self._proxied_transaction + assert t is not None + t.rollback() + self.migration_context._transaction = None + + def commit(self) -> None: + t = self._proxied_transaction + assert t is not None + t.commit() + self.migration_context._transaction = None + + def __enter__(self) -> _ProxyTransaction: + return self + + def __exit__(self, type_: Any, value: Any, traceback: Any) -> None: + if self._proxied_transaction is not None: + self._proxied_transaction.__exit__(type_, value, traceback) + self.migration_context._transaction = None + + +class MigrationContext: + + """Represent the database state made available to a migration + script. + + :class:`.MigrationContext` is the front end to an actual + database connection, or alternatively a string output + stream given a particular database dialect, + from an Alembic perspective. + + When inside the ``env.py`` script, the :class:`.MigrationContext` + is available via the + :meth:`.EnvironmentContext.get_context` method, + which is available at ``alembic.context``:: + + # from within env.py script + from alembic import context + + migration_context = context.get_context() + + For usage outside of an ``env.py`` script, such as for + utility routines that want to check the current version + in the database, the :meth:`.MigrationContext.configure` + method to create new :class:`.MigrationContext` objects. + For example, to get at the current revision in the + database using :meth:`.MigrationContext.get_current_revision`:: + + # in any application, outside of an env.py script + from alembic.migration import MigrationContext + from sqlalchemy import create_engine + + engine = create_engine("postgresql://mydatabase") + conn = engine.connect() + + context = MigrationContext.configure(conn) + current_rev = context.get_current_revision() + + The above context can also be used to produce + Alembic migration operations with an :class:`.Operations` + instance:: + + # in any application, outside of the normal Alembic environment + from alembic.operations import Operations + + op = Operations(context) + op.alter_column("mytable", "somecolumn", nullable=True) + + """ + + def __init__( + self, + dialect: Dialect, + connection: Optional[Connection], + opts: Dict[str, Any], + environment_context: Optional[EnvironmentContext] = None, + ) -> None: + self.environment_context = environment_context + self.opts = opts + self.dialect = dialect + self.script: Optional[ScriptDirectory] = opts.get("script") + as_sql: bool = opts.get("as_sql", False) + transactional_ddl = opts.get("transactional_ddl") + self._transaction_per_migration = opts.get( + "transaction_per_migration", False + ) + self.on_version_apply_callbacks = opts.get("on_version_apply", ()) + self._transaction: Optional[Transaction] = None + + if as_sql: + self.connection = cast( + Optional["Connection"], self._stdout_connection(connection) + ) + assert self.connection is not None + self._in_external_transaction = False + else: + self.connection = connection + self._in_external_transaction = ( + sqla_compat._get_connection_in_transaction(connection) + ) + + self._migrations_fn: Optional[ + Callable[..., Iterable[RevisionStep]] + ] = opts.get("fn") + self.as_sql = as_sql + + self.purge = opts.get("purge", False) + + if "output_encoding" in opts: + self.output_buffer = EncodedIO( + opts.get("output_buffer") + or sys.stdout, # type:ignore[arg-type] + opts["output_encoding"], + ) + else: + self.output_buffer = opts.get("output_buffer", sys.stdout) + + self._user_compare_type = opts.get("compare_type", True) + self._user_compare_server_default = opts.get( + "compare_server_default", False + ) + self.version_table = version_table = opts.get( + "version_table", "alembic_version" + ) + self.version_table_schema = version_table_schema = opts.get( + "version_table_schema", None + ) + self._version = Table( + version_table, + MetaData(), + Column("version_num", String(32), nullable=False), + schema=version_table_schema, + ) + if opts.get("version_table_pk", True): + self._version.append_constraint( + PrimaryKeyConstraint( + "version_num", name="%s_pkc" % version_table + ) + ) + + self._start_from_rev: Optional[str] = opts.get("starting_rev") + self.impl = ddl.DefaultImpl.get_by_dialect(dialect)( + dialect, + self.connection, + self.as_sql, + transactional_ddl, + self.output_buffer, + opts, + ) + log.info("Context impl %s.", self.impl.__class__.__name__) + if self.as_sql: + log.info("Generating static SQL") + log.info( + "Will assume %s DDL.", + "transactional" + if self.impl.transactional_ddl + else "non-transactional", + ) + + @classmethod + def configure( + cls, + connection: Optional[Connection] = None, + url: Optional[Union[str, URL]] = None, + dialect_name: Optional[str] = None, + dialect: Optional[Dialect] = None, + environment_context: Optional[EnvironmentContext] = None, + dialect_opts: Optional[Dict[str, str]] = None, + opts: Optional[Any] = None, + ) -> MigrationContext: + """Create a new :class:`.MigrationContext`. + + This is a factory method usually called + by :meth:`.EnvironmentContext.configure`. + + :param connection: a :class:`~sqlalchemy.engine.Connection` + to use for SQL execution in "online" mode. When present, + is also used to determine the type of dialect in use. + :param url: a string database url, or a + :class:`sqlalchemy.engine.url.URL` object. + The type of dialect to be used will be derived from this if + ``connection`` is not passed. + :param dialect_name: string name of a dialect, such as + "postgresql", "mssql", etc. The type of dialect to be used will be + derived from this if ``connection`` and ``url`` are not passed. + :param opts: dictionary of options. Most other options + accepted by :meth:`.EnvironmentContext.configure` are passed via + this dictionary. + + """ + if opts is None: + opts = {} + if dialect_opts is None: + dialect_opts = {} + + if connection: + if isinstance(connection, Engine): + raise util.CommandError( + "'connection' argument to configure() is expected " + "to be a sqlalchemy.engine.Connection instance, " + "got %r" % connection, + ) + + dialect = connection.dialect + elif url: + url_obj = sqla_url.make_url(url) + dialect = url_obj.get_dialect()(**dialect_opts) + elif dialect_name: + url_obj = sqla_url.make_url("%s://" % dialect_name) + dialect = url_obj.get_dialect()(**dialect_opts) + elif not dialect: + raise Exception("Connection, url, or dialect_name is required.") + assert dialect is not None + return MigrationContext(dialect, connection, opts, environment_context) + + @contextmanager + def autocommit_block(self) -> Iterator[None]: + """Enter an "autocommit" block, for databases that support AUTOCOMMIT + isolation levels. + + This special directive is intended to support the occasional database + DDL or system operation that specifically has to be run outside of + any kind of transaction block. The PostgreSQL database platform + is the most common target for this style of operation, as many + of its DDL operations must be run outside of transaction blocks, even + though the database overall supports transactional DDL. + + The method is used as a context manager within a migration script, by + calling on :meth:`.Operations.get_context` to retrieve the + :class:`.MigrationContext`, then invoking + :meth:`.MigrationContext.autocommit_block` using the ``with:`` + statement:: + + def upgrade(): + with op.get_context().autocommit_block(): + op.execute("ALTER TYPE mood ADD VALUE 'soso'") + + Above, a PostgreSQL "ALTER TYPE..ADD VALUE" directive is emitted, + which must be run outside of a transaction block at the database level. + The :meth:`.MigrationContext.autocommit_block` method makes use of the + SQLAlchemy ``AUTOCOMMIT`` isolation level setting, which against the + psycogp2 DBAPI corresponds to the ``connection.autocommit`` setting, + to ensure that the database driver is not inside of a DBAPI level + transaction block. + + .. warning:: + + As is necessary, **the database transaction preceding the block is + unconditionally committed**. This means that the run of migrations + preceding the operation will be committed, before the overall + migration operation is complete. + + It is recommended that when an application includes migrations with + "autocommit" blocks, that + :paramref:`.EnvironmentContext.transaction_per_migration` be used + so that the calling environment is tuned to expect short per-file + migrations whether or not one of them has an autocommit block. + + + """ + _in_connection_transaction = self._in_connection_transaction() + + if self.impl.transactional_ddl and self.as_sql: + self.impl.emit_commit() + + elif _in_connection_transaction: + assert self._transaction is not None + + self._transaction.commit() + self._transaction = None + + if not self.as_sql: + assert self.connection is not None + current_level = self.connection.get_isolation_level() + base_connection = self.connection + + # in 1.3 and 1.4 non-future mode, the connection gets switched + # out. we can use the base connection with the new mode + # except that it will not know it's in "autocommit" and will + # emit deprecation warnings when an autocommit action takes + # place. + self.connection = ( + self.impl.connection + ) = base_connection.execution_options(isolation_level="AUTOCOMMIT") + + # sqlalchemy future mode will "autobegin" in any case, so take + # control of that "transaction" here + fake_trans: Optional[Transaction] = self.connection.begin() + else: + fake_trans = None + try: + yield + finally: + if not self.as_sql: + assert self.connection is not None + if fake_trans is not None: + fake_trans.commit() + self.connection.execution_options( + isolation_level=current_level + ) + self.connection = self.impl.connection = base_connection + + if self.impl.transactional_ddl and self.as_sql: + self.impl.emit_begin() + + elif _in_connection_transaction: + assert self.connection is not None + self._transaction = self.connection.begin() + + def begin_transaction( + self, _per_migration: bool = False + ) -> Union[_ProxyTransaction, ContextManager[None]]: + """Begin a logical transaction for migration operations. + + This method is used within an ``env.py`` script to demarcate where + the outer "transaction" for a series of migrations begins. Example:: + + def run_migrations_online(): + connectable = create_engine(...) + + with connectable.connect() as connection: + context.configure( + connection=connection, target_metadata=target_metadata + ) + + with context.begin_transaction(): + context.run_migrations() + + Above, :meth:`.MigrationContext.begin_transaction` is used to demarcate + where the outer logical transaction occurs around the + :meth:`.MigrationContext.run_migrations` operation. + + A "Logical" transaction means that the operation may or may not + correspond to a real database transaction. If the target database + supports transactional DDL (or + :paramref:`.EnvironmentContext.configure.transactional_ddl` is true), + the :paramref:`.EnvironmentContext.configure.transaction_per_migration` + flag is not set, and the migration is against a real database + connection (as opposed to using "offline" ``--sql`` mode), a real + transaction will be started. If ``--sql`` mode is in effect, the + operation would instead correspond to a string such as "BEGIN" being + emitted to the string output. + + The returned object is a Python context manager that should only be + used in the context of a ``with:`` statement as indicated above. + The object has no other guaranteed API features present. + + .. seealso:: + + :meth:`.MigrationContext.autocommit_block` + + """ + + if self._in_external_transaction: + return nullcontext() + + if self.impl.transactional_ddl: + transaction_now = _per_migration == self._transaction_per_migration + else: + transaction_now = _per_migration is True + + if not transaction_now: + return nullcontext() + + elif not self.impl.transactional_ddl: + assert _per_migration + + if self.as_sql: + return nullcontext() + else: + # track our own notion of a "transaction block", which must be + # committed when complete. Don't rely upon whether or not the + # SQLAlchemy connection reports as "in transaction"; this + # because SQLAlchemy future connection features autobegin + # behavior, so it may already be in a transaction from our + # emitting of queries like "has_version_table", etc. While we + # could track these operations as well, that leaves open the + # possibility of new operations or other things happening in + # the user environment that still may be triggering + # "autobegin". + + in_transaction = self._transaction is not None + + if in_transaction: + return nullcontext() + else: + assert self.connection is not None + self._transaction = ( + sqla_compat._safe_begin_connection_transaction( + self.connection + ) + ) + return _ProxyTransaction(self) + elif self.as_sql: + + @contextmanager + def begin_commit(): + self.impl.emit_begin() + yield + self.impl.emit_commit() + + return begin_commit() + else: + assert self.connection is not None + self._transaction = sqla_compat._safe_begin_connection_transaction( + self.connection + ) + return _ProxyTransaction(self) + + def get_current_revision(self) -> Optional[str]: + """Return the current revision, usually that which is present + in the ``alembic_version`` table in the database. + + This method intends to be used only for a migration stream that + does not contain unmerged branches in the target database; + if there are multiple branches present, an exception is raised. + The :meth:`.MigrationContext.get_current_heads` should be preferred + over this method going forward in order to be compatible with + branch migration support. + + If this :class:`.MigrationContext` was configured in "offline" + mode, that is with ``as_sql=True``, the ``starting_rev`` + parameter is returned instead, if any. + + """ + heads = self.get_current_heads() + if len(heads) == 0: + return None + elif len(heads) > 1: + raise util.CommandError( + "Version table '%s' has more than one head present; " + "please use get_current_heads()" % self.version_table + ) + else: + return heads[0] + + def get_current_heads(self) -> Tuple[str, ...]: + """Return a tuple of the current 'head versions' that are represented + in the target database. + + For a migration stream without branches, this will be a single + value, synonymous with that of + :meth:`.MigrationContext.get_current_revision`. However when multiple + unmerged branches exist within the target database, the returned tuple + will contain a value for each head. + + If this :class:`.MigrationContext` was configured in "offline" + mode, that is with ``as_sql=True``, the ``starting_rev`` + parameter is returned in a one-length tuple. + + If no version table is present, or if there are no revisions + present, an empty tuple is returned. + + """ + if self.as_sql: + start_from_rev: Any = self._start_from_rev + if start_from_rev == "base": + start_from_rev = None + elif start_from_rev is not None and self.script: + start_from_rev = [ + self.script.get_revision(sfr).revision + for sfr in util.to_list(start_from_rev) + if sfr not in (None, "base") + ] + return util.to_tuple(start_from_rev, default=()) + else: + if self._start_from_rev: + raise util.CommandError( + "Can't specify current_rev to context " + "when using a database connection" + ) + if not self._has_version_table(): + return () + assert self.connection is not None + return tuple( + row[0] for row in self.connection.execute(self._version.select()) + ) + + def _ensure_version_table(self, purge: bool = False) -> None: + with sqla_compat._ensure_scope_for_ddl(self.connection): + assert self.connection is not None + self._version.create(self.connection, checkfirst=True) + if purge: + assert self.connection is not None + self.connection.execute(self._version.delete()) + + def _has_version_table(self) -> bool: + assert self.connection is not None + return sqla_compat._connectable_has_table( + self.connection, self.version_table, self.version_table_schema + ) + + def stamp(self, script_directory: ScriptDirectory, revision: str) -> None: + """Stamp the version table with a specific revision. + + This method calculates those branches to which the given revision + can apply, and updates those branches as though they were migrated + towards that revision (either up or down). If no current branches + include the revision, it is added as a new branch head. + + """ + heads = self.get_current_heads() + if not self.as_sql and not heads: + self._ensure_version_table() + head_maintainer = HeadMaintainer(self, heads) + for step in script_directory._stamp_revs(revision, heads): + head_maintainer.update_to_step(step) + + def run_migrations(self, **kw: Any) -> None: + r"""Run the migration scripts established for this + :class:`.MigrationContext`, if any. + + The commands in :mod:`alembic.command` will set up a function + that is ultimately passed to the :class:`.MigrationContext` + as the ``fn`` argument. This function represents the "work" + that will be done when :meth:`.MigrationContext.run_migrations` + is called, typically from within the ``env.py`` script of the + migration environment. The "work function" then provides an iterable + of version callables and other version information which + in the case of the ``upgrade`` or ``downgrade`` commands are the + list of version scripts to invoke. Other commands yield nothing, + in the case that a command wants to run some other operation + against the database such as the ``current`` or ``stamp`` commands. + + :param \**kw: keyword arguments here will be passed to each + migration callable, that is the ``upgrade()`` or ``downgrade()`` + method within revision scripts. + + """ + self.impl.start_migrations() + + heads: Tuple[str, ...] + if self.purge: + if self.as_sql: + raise util.CommandError("Can't use --purge with --sql mode") + self._ensure_version_table(purge=True) + heads = () + else: + heads = self.get_current_heads() + + dont_mutate = self.opts.get("dont_mutate", False) + + if not self.as_sql and not heads and not dont_mutate: + self._ensure_version_table() + + head_maintainer = HeadMaintainer(self, heads) + + assert self._migrations_fn is not None + for step in self._migrations_fn(heads, self): + with self.begin_transaction(_per_migration=True): + if self.as_sql and not head_maintainer.heads: + # for offline mode, include a CREATE TABLE from + # the base + assert self.connection is not None + self._version.create(self.connection) + log.info("Running %s", step) + if self.as_sql: + self.impl.static_output( + "-- Running %s" % (step.short_log,) + ) + step.migration_fn(**kw) + + # previously, we wouldn't stamp per migration + # if we were in a transaction, however given the more + # complex model that involves any number of inserts + # and row-targeted updates and deletes, it's simpler for now + # just to run the operations on every version + head_maintainer.update_to_step(step) + for callback in self.on_version_apply_callbacks: + callback( + ctx=self, + step=step.info, + heads=set(head_maintainer.heads), + run_args=kw, + ) + + if self.as_sql and not head_maintainer.heads: + assert self.connection is not None + self._version.drop(self.connection) + + def _in_connection_transaction(self) -> bool: + try: + meth = self.connection.in_transaction # type:ignore[union-attr] + except AttributeError: + return False + else: + return meth() + + def execute( + self, + sql: Union[Executable, str], + execution_options: Optional[Dict[str, Any]] = None, + ) -> None: + """Execute a SQL construct or string statement. + + The underlying execution mechanics are used, that is + if this is "offline mode" the SQL is written to the + output buffer, otherwise the SQL is emitted on + the current SQLAlchemy connection. + + """ + self.impl._exec(sql, execution_options) + + def _stdout_connection( + self, connection: Optional[Connection] + ) -> MockConnection: + def dump(construct, *multiparams, **params): + self.impl._exec(construct) + + return MockEngineStrategy.MockConnection(self.dialect, dump) + + @property + def bind(self) -> Optional[Connection]: + """Return the current "bind". + + In online mode, this is an instance of + :class:`sqlalchemy.engine.Connection`, and is suitable + for ad-hoc execution of any kind of usage described + in SQLAlchemy Core documentation as well as + for usage with the :meth:`sqlalchemy.schema.Table.create` + and :meth:`sqlalchemy.schema.MetaData.create_all` methods + of :class:`~sqlalchemy.schema.Table`, + :class:`~sqlalchemy.schema.MetaData`. + + Note that when "standard output" mode is enabled, + this bind will be a "mock" connection handler that cannot + return results and is only appropriate for a very limited + subset of commands. + + """ + return self.connection + + @property + def config(self) -> Optional[Config]: + """Return the :class:`.Config` used by the current environment, + if any.""" + + if self.environment_context: + return self.environment_context.config + else: + return None + + def _compare_type( + self, inspector_column: Column[Any], metadata_column: Column + ) -> bool: + if self._user_compare_type is False: + return False + + if callable(self._user_compare_type): + user_value = self._user_compare_type( + self, + inspector_column, + metadata_column, + inspector_column.type, + metadata_column.type, + ) + if user_value is not None: + return user_value + + return self.impl.compare_type(inspector_column, metadata_column) + + def _compare_server_default( + self, + inspector_column: Column[Any], + metadata_column: Column[Any], + rendered_metadata_default: Optional[str], + rendered_column_default: Optional[str], + ) -> bool: + if self._user_compare_server_default is False: + return False + + if callable(self._user_compare_server_default): + user_value = self._user_compare_server_default( + self, + inspector_column, + metadata_column, + rendered_column_default, + metadata_column.server_default, + rendered_metadata_default, + ) + if user_value is not None: + return user_value + + return self.impl.compare_server_default( + inspector_column, + metadata_column, + rendered_metadata_default, + rendered_column_default, + ) + + +class HeadMaintainer: + def __init__(self, context: MigrationContext, heads: Any) -> None: + self.context = context + self.heads = set(heads) + + def _insert_version(self, version: str) -> None: + assert version not in self.heads + self.heads.add(version) + + self.context.impl._exec( + self.context._version.insert().values( + version_num=literal_column("'%s'" % version) + ) + ) + + def _delete_version(self, version: str) -> None: + self.heads.remove(version) + + ret = self.context.impl._exec( + self.context._version.delete().where( + self.context._version.c.version_num + == literal_column("'%s'" % version) + ) + ) + + if ( + not self.context.as_sql + and self.context.dialect.supports_sane_rowcount + and ret is not None + and ret.rowcount != 1 + ): + raise util.CommandError( + "Online migration expected to match one " + "row when deleting '%s' in '%s'; " + "%d found" + % (version, self.context.version_table, ret.rowcount) + ) + + def _update_version(self, from_: str, to_: str) -> None: + assert to_ not in self.heads + self.heads.remove(from_) + self.heads.add(to_) + + ret = self.context.impl._exec( + self.context._version.update() + .values(version_num=literal_column("'%s'" % to_)) + .where( + self.context._version.c.version_num + == literal_column("'%s'" % from_) + ) + ) + + if ( + not self.context.as_sql + and self.context.dialect.supports_sane_rowcount + and ret is not None + and ret.rowcount != 1 + ): + raise util.CommandError( + "Online migration expected to match one " + "row when updating '%s' to '%s' in '%s'; " + "%d found" + % (from_, to_, self.context.version_table, ret.rowcount) + ) + + def update_to_step(self, step: Union[RevisionStep, StampStep]) -> None: + if step.should_delete_branch(self.heads): + vers = step.delete_version_num + log.debug("branch delete %s", vers) + self._delete_version(vers) + elif step.should_create_branch(self.heads): + vers = step.insert_version_num + log.debug("new branch insert %s", vers) + self._insert_version(vers) + elif step.should_merge_branches(self.heads): + # delete revs, update from rev, update to rev + ( + delete_revs, + update_from_rev, + update_to_rev, + ) = step.merge_branch_idents(self.heads) + log.debug( + "merge, delete %s, update %s to %s", + delete_revs, + update_from_rev, + update_to_rev, + ) + for delrev in delete_revs: + self._delete_version(delrev) + self._update_version(update_from_rev, update_to_rev) + elif step.should_unmerge_branches(self.heads): + ( + update_from_rev, + update_to_rev, + insert_revs, + ) = step.unmerge_branch_idents(self.heads) + log.debug( + "unmerge, insert %s, update %s to %s", + insert_revs, + update_from_rev, + update_to_rev, + ) + for insrev in insert_revs: + self._insert_version(insrev) + self._update_version(update_from_rev, update_to_rev) + else: + from_, to_ = step.update_version_num(self.heads) + log.debug("update %s to %s", from_, to_) + self._update_version(from_, to_) + + +class MigrationInfo: + """Exposes information about a migration step to a callback listener. + + The :class:`.MigrationInfo` object is available exclusively for the + benefit of the :paramref:`.EnvironmentContext.on_version_apply` + callback hook. + + """ + + is_upgrade: bool + """True/False: indicates whether this operation ascends or descends the + version tree.""" + + is_stamp: bool + """True/False: indicates whether this operation is a stamp (i.e. whether + it results in any actual database operations).""" + + up_revision_id: Optional[str] + """Version string corresponding to :attr:`.Revision.revision`. + + In the case of a stamp operation, it is advised to use the + :attr:`.MigrationInfo.up_revision_ids` tuple as a stamp operation can + make a single movement from one or more branches down to a single + branchpoint, in which case there will be multiple "up" revisions. + + .. seealso:: + + :attr:`.MigrationInfo.up_revision_ids` + + """ + + up_revision_ids: Tuple[str, ...] + """Tuple of version strings corresponding to :attr:`.Revision.revision`. + + In the majority of cases, this tuple will be a single value, synonymous + with the scalar value of :attr:`.MigrationInfo.up_revision_id`. + It can be multiple revision identifiers only in the case of an + ``alembic stamp`` operation which is moving downwards from multiple + branches down to their common branch point. + + """ + + down_revision_ids: Tuple[str, ...] + """Tuple of strings representing the base revisions of this migration step. + + If empty, this represents a root revision; otherwise, the first item + corresponds to :attr:`.Revision.down_revision`, and the rest are inferred + from dependencies. + """ + + revision_map: RevisionMap + """The revision map inside of which this operation occurs.""" + + def __init__( + self, + revision_map: RevisionMap, + is_upgrade: bool, + is_stamp: bool, + up_revisions: Union[str, Tuple[str, ...]], + down_revisions: Union[str, Tuple[str, ...]], + ) -> None: + self.revision_map = revision_map + self.is_upgrade = is_upgrade + self.is_stamp = is_stamp + self.up_revision_ids = util.to_tuple(up_revisions, default=()) + if self.up_revision_ids: + self.up_revision_id = self.up_revision_ids[0] + else: + # this should never be the case with + # "upgrade", "downgrade", or "stamp" as we are always + # measuring movement in terms of at least one upgrade version + self.up_revision_id = None + self.down_revision_ids = util.to_tuple(down_revisions, default=()) + + @property + def is_migration(self) -> bool: + """True/False: indicates whether this operation is a migration. + + At present this is true if and only the migration is not a stamp. + If other operation types are added in the future, both this attribute + and :attr:`~.MigrationInfo.is_stamp` will be false. + """ + return not self.is_stamp + + @property + def source_revision_ids(self) -> Tuple[str, ...]: + """Active revisions before this migration step is applied.""" + return ( + self.down_revision_ids if self.is_upgrade else self.up_revision_ids + ) + + @property + def destination_revision_ids(self) -> Tuple[str, ...]: + """Active revisions after this migration step is applied.""" + return ( + self.up_revision_ids if self.is_upgrade else self.down_revision_ids + ) + + @property + def up_revision(self) -> Optional[Revision]: + """Get :attr:`~.MigrationInfo.up_revision_id` as + a :class:`.Revision`. + + """ + return self.revision_map.get_revision(self.up_revision_id) + + @property + def up_revisions(self) -> Tuple[Optional[_RevisionOrBase], ...]: + """Get :attr:`~.MigrationInfo.up_revision_ids` as a + :class:`.Revision`.""" + return self.revision_map.get_revisions(self.up_revision_ids) + + @property + def down_revisions(self) -> Tuple[Optional[_RevisionOrBase], ...]: + """Get :attr:`~.MigrationInfo.down_revision_ids` as a tuple of + :class:`Revisions <.Revision>`.""" + return self.revision_map.get_revisions(self.down_revision_ids) + + @property + def source_revisions(self) -> Tuple[Optional[_RevisionOrBase], ...]: + """Get :attr:`~MigrationInfo.source_revision_ids` as a tuple of + :class:`Revisions <.Revision>`.""" + return self.revision_map.get_revisions(self.source_revision_ids) + + @property + def destination_revisions(self) -> Tuple[Optional[_RevisionOrBase], ...]: + """Get :attr:`~MigrationInfo.destination_revision_ids` as a tuple of + :class:`Revisions <.Revision>`.""" + return self.revision_map.get_revisions(self.destination_revision_ids) + + +class MigrationStep: + from_revisions_no_deps: Tuple[str, ...] + to_revisions_no_deps: Tuple[str, ...] + is_upgrade: bool + migration_fn: Any + + if TYPE_CHECKING: + + @property + def doc(self) -> Optional[str]: + ... + + @property + def name(self) -> str: + return self.migration_fn.__name__ + + @classmethod + def upgrade_from_script( + cls, revision_map: RevisionMap, script: Script + ) -> RevisionStep: + return RevisionStep(revision_map, script, True) + + @classmethod + def downgrade_from_script( + cls, revision_map: RevisionMap, script: Script + ) -> RevisionStep: + return RevisionStep(revision_map, script, False) + + @property + def is_downgrade(self) -> bool: + return not self.is_upgrade + + @property + def short_log(self) -> str: + return "%s %s -> %s" % ( + self.name, + util.format_as_comma(self.from_revisions_no_deps), + util.format_as_comma(self.to_revisions_no_deps), + ) + + def __str__(self): + if self.doc: + return "%s %s -> %s, %s" % ( + self.name, + util.format_as_comma(self.from_revisions_no_deps), + util.format_as_comma(self.to_revisions_no_deps), + self.doc, + ) + else: + return self.short_log + + +class RevisionStep(MigrationStep): + def __init__( + self, revision_map: RevisionMap, revision: Script, is_upgrade: bool + ) -> None: + self.revision_map = revision_map + self.revision = revision + self.is_upgrade = is_upgrade + if is_upgrade: + self.migration_fn = revision.module.upgrade + else: + self.migration_fn = revision.module.downgrade + + def __repr__(self): + return "RevisionStep(%r, is_upgrade=%r)" % ( + self.revision.revision, + self.is_upgrade, + ) + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, RevisionStep) + and other.revision == self.revision + and self.is_upgrade == other.is_upgrade + ) + + @property + def doc(self) -> Optional[str]: + return self.revision.doc + + @property + def from_revisions(self) -> Tuple[str, ...]: + if self.is_upgrade: + return self.revision._normalized_down_revisions + else: + return (self.revision.revision,) + + @property + def from_revisions_no_deps( # type:ignore[override] + self, + ) -> Tuple[str, ...]: + if self.is_upgrade: + return self.revision._versioned_down_revisions + else: + return (self.revision.revision,) + + @property + def to_revisions(self) -> Tuple[str, ...]: + if self.is_upgrade: + return (self.revision.revision,) + else: + return self.revision._normalized_down_revisions + + @property + def to_revisions_no_deps( # type:ignore[override] + self, + ) -> Tuple[str, ...]: + if self.is_upgrade: + return (self.revision.revision,) + else: + return self.revision._versioned_down_revisions + + @property + def _has_scalar_down_revision(self) -> bool: + return len(self.revision._normalized_down_revisions) == 1 + + def should_delete_branch(self, heads: Set[str]) -> bool: + """A delete is when we are a. in a downgrade and b. + we are going to the "base" or we are going to a version that + is implied as a dependency on another version that is remaining. + + """ + if not self.is_downgrade: + return False + + if self.revision.revision not in heads: + return False + + downrevs = self.revision._normalized_down_revisions + + if not downrevs: + # is a base + return True + else: + # determine what the ultimate "to_revisions" for an + # unmerge would be. If there are none, then we're a delete. + to_revisions = self._unmerge_to_revisions(heads) + return not to_revisions + + def merge_branch_idents( + self, heads: Set[str] + ) -> Tuple[List[str], str, str]: + other_heads = set(heads).difference(self.from_revisions) + + if other_heads: + ancestors = { + r.revision + for r in self.revision_map._get_ancestor_nodes( + self.revision_map.get_revisions(other_heads), check=False + ) + } + from_revisions = list( + set(self.from_revisions).difference(ancestors) + ) + else: + from_revisions = list(self.from_revisions) + + return ( + # delete revs, update from rev, update to rev + list(from_revisions[0:-1]), + from_revisions[-1], + self.to_revisions[0], + ) + + def _unmerge_to_revisions(self, heads: Set[str]) -> Tuple[str, ...]: + other_heads = set(heads).difference([self.revision.revision]) + if other_heads: + ancestors = { + r.revision + for r in self.revision_map._get_ancestor_nodes( + self.revision_map.get_revisions(other_heads), check=False + ) + } + return tuple(set(self.to_revisions).difference(ancestors)) + else: + # for each revision we plan to return, compute its ancestors + # (excluding self), and remove those from the final output since + # they are already accounted for. + ancestors = { + r.revision + for to_revision in self.to_revisions + for r in self.revision_map._get_ancestor_nodes( + self.revision_map.get_revisions(to_revision), check=False + ) + if r.revision != to_revision + } + return tuple(set(self.to_revisions).difference(ancestors)) + + def unmerge_branch_idents( + self, heads: Set[str] + ) -> Tuple[str, str, Tuple[str, ...]]: + to_revisions = self._unmerge_to_revisions(heads) + + return ( + # update from rev, update to rev, insert revs + self.from_revisions[0], + to_revisions[-1], + to_revisions[0:-1], + ) + + def should_create_branch(self, heads: Set[str]) -> bool: + if not self.is_upgrade: + return False + + downrevs = self.revision._normalized_down_revisions + + if not downrevs: + # is a base + return True + else: + # none of our downrevs are present, so... + # we have to insert our version. This is true whether + # or not there is only one downrev, or multiple (in the latter + # case, we're a merge point.) + if not heads.intersection(downrevs): + return True + else: + return False + + def should_merge_branches(self, heads: Set[str]) -> bool: + if not self.is_upgrade: + return False + + downrevs = self.revision._normalized_down_revisions + + if len(downrevs) > 1 and len(heads.intersection(downrevs)) > 1: + return True + + return False + + def should_unmerge_branches(self, heads: Set[str]) -> bool: + if not self.is_downgrade: + return False + + downrevs = self.revision._normalized_down_revisions + + if self.revision.revision in heads and len(downrevs) > 1: + return True + + return False + + def update_version_num(self, heads: Set[str]) -> Tuple[str, str]: + if not self._has_scalar_down_revision: + downrev = heads.intersection( + self.revision._normalized_down_revisions + ) + assert ( + len(downrev) == 1 + ), "Can't do an UPDATE because downrevision is ambiguous" + down_revision = list(downrev)[0] + else: + down_revision = self.revision._normalized_down_revisions[0] + + if self.is_upgrade: + return down_revision, self.revision.revision + else: + return self.revision.revision, down_revision + + @property + def delete_version_num(self) -> str: + return self.revision.revision + + @property + def insert_version_num(self) -> str: + return self.revision.revision + + @property + def info(self) -> MigrationInfo: + return MigrationInfo( + revision_map=self.revision_map, + up_revisions=self.revision.revision, + down_revisions=self.revision._normalized_down_revisions, + is_upgrade=self.is_upgrade, + is_stamp=False, + ) + + +class StampStep(MigrationStep): + def __init__( + self, + from_: Optional[Union[str, Collection[str]]], + to_: Optional[Union[str, Collection[str]]], + is_upgrade: bool, + branch_move: bool, + revision_map: Optional[RevisionMap] = None, + ) -> None: + self.from_: Tuple[str, ...] = util.to_tuple(from_, default=()) + self.to_: Tuple[str, ...] = util.to_tuple(to_, default=()) + self.is_upgrade = is_upgrade + self.branch_move = branch_move + self.migration_fn = self.stamp_revision + self.revision_map = revision_map + + doc: Optional[str] = None + + def stamp_revision(self, **kw: Any) -> None: + return None + + def __eq__(self, other): + return ( + isinstance(other, StampStep) + and other.from_revisions == self.from_revisions + and other.to_revisions == self.to_revisions + and other.branch_move == self.branch_move + and self.is_upgrade == other.is_upgrade + ) + + @property + def from_revisions(self): + return self.from_ + + @property + def to_revisions(self) -> Tuple[str, ...]: + return self.to_ + + @property + def from_revisions_no_deps( # type:ignore[override] + self, + ) -> Tuple[str, ...]: + return self.from_ + + @property + def to_revisions_no_deps( # type:ignore[override] + self, + ) -> Tuple[str, ...]: + return self.to_ + + @property + def delete_version_num(self) -> str: + assert len(self.from_) == 1 + return self.from_[0] + + @property + def insert_version_num(self) -> str: + assert len(self.to_) == 1 + return self.to_[0] + + def update_version_num(self, heads: Set[str]) -> Tuple[str, str]: + assert len(self.from_) == 1 + assert len(self.to_) == 1 + return self.from_[0], self.to_[0] + + def merge_branch_idents( + self, heads: Union[Set[str], List[str]] + ) -> Union[Tuple[List[Any], str, str], Tuple[List[str], str, str]]: + return ( + # delete revs, update from rev, update to rev + list(self.from_[0:-1]), + self.from_[-1], + self.to_[0], + ) + + def unmerge_branch_idents( + self, heads: Set[str] + ) -> Tuple[str, str, List[str]]: + return ( + # update from rev, update to rev, insert revs + self.from_[0], + self.to_[-1], + list(self.to_[0:-1]), + ) + + def should_delete_branch(self, heads: Set[str]) -> bool: + # TODO: we probably need to look for self.to_ inside of heads, + # in a similar manner as should_create_branch, however we have + # no tests for this yet (stamp downgrades w/ branches) + return self.is_downgrade and self.branch_move + + def should_create_branch(self, heads: Set[str]) -> Union[Set[str], bool]: + return ( + self.is_upgrade + and (self.branch_move or set(self.from_).difference(heads)) + and set(self.to_).difference(heads) + ) + + def should_merge_branches(self, heads: Set[str]) -> bool: + return len(self.from_) > 1 + + def should_unmerge_branches(self, heads: Set[str]) -> bool: + return len(self.to_) > 1 + + @property + def info(self) -> MigrationInfo: + up, down = ( + (self.to_, self.from_) + if self.is_upgrade + else (self.from_, self.to_) + ) + assert self.revision_map is not None + return MigrationInfo( + revision_map=self.revision_map, + up_revisions=up, + down_revisions=down, + is_upgrade=self.is_upgrade, + is_stamp=True, + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d78f3f1dc54c13a52b64e8d668c2baf708eb20bc --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/__init__.py @@ -0,0 +1,4 @@ +from .base import Script +from .base import ScriptDirectory + +__all__ = ["ScriptDirectory", "Script"] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/base.py new file mode 100644 index 0000000000000000000000000000000000000000..5945ca591c221279b05b07833591faa4ad4cd628 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/base.py @@ -0,0 +1,1060 @@ +from __future__ import annotations + +from contextlib import contextmanager +import datetime +import os +import re +import shutil +import sys +from types import ModuleType +from typing import Any +from typing import cast +from typing import Iterator +from typing import List +from typing import Mapping +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import TYPE_CHECKING +from typing import Union + +from . import revision +from . import write_hooks +from .. import util +from ..runtime import migration +from ..util import compat +from ..util import not_none + +if TYPE_CHECKING: + from .revision import _GetRevArg + from .revision import _RevIdType + from .revision import Revision + from ..config import Config + from ..config import MessagingOptions + from ..runtime.migration import RevisionStep + from ..runtime.migration import StampStep + +try: + if compat.py39: + from zoneinfo import ZoneInfo + from zoneinfo import ZoneInfoNotFoundError + else: + from backports.zoneinfo import ZoneInfo # type: ignore[import-not-found,no-redef] # noqa: E501 + from backports.zoneinfo import ZoneInfoNotFoundError # type: ignore[no-redef] # noqa: E501 +except ImportError: + ZoneInfo = None # type: ignore[assignment, misc] + +_sourceless_rev_file = re.compile(r"(?!\.\#|__init__)(.*\.py)(c|o)?$") +_only_source_rev_file = re.compile(r"(?!\.\#|__init__)(.*\.py)$") +_legacy_rev = re.compile(r"([a-f0-9]+)\.py$") +_slug_re = re.compile(r"\w+") +_default_file_template = "%(rev)s_%(slug)s" +_split_on_space_comma = re.compile(r", *|(?: +)") + +_split_on_space_comma_colon = re.compile(r", *|(?: +)|\:") + + +class ScriptDirectory: + + """Provides operations upon an Alembic script directory. + + This object is useful to get information as to current revisions, + most notably being able to get at the "head" revision, for schemes + that want to test if the current revision in the database is the most + recent:: + + from alembic.script import ScriptDirectory + from alembic.config import Config + config = Config() + config.set_main_option("script_location", "myapp:migrations") + script = ScriptDirectory.from_config(config) + + head_revision = script.get_current_head() + + + + """ + + def __init__( + self, + dir: str, # noqa + file_template: str = _default_file_template, + truncate_slug_length: Optional[int] = 40, + version_locations: Optional[List[str]] = None, + sourceless: bool = False, + output_encoding: str = "utf-8", + timezone: Optional[str] = None, + hook_config: Optional[Mapping[str, str]] = None, + recursive_version_locations: bool = False, + messaging_opts: MessagingOptions = cast( + "MessagingOptions", util.EMPTY_DICT + ), + ) -> None: + self.dir = dir + self.file_template = file_template + self.version_locations = version_locations + self.truncate_slug_length = truncate_slug_length or 40 + self.sourceless = sourceless + self.output_encoding = output_encoding + self.revision_map = revision.RevisionMap(self._load_revisions) + self.timezone = timezone + self.hook_config = hook_config + self.recursive_version_locations = recursive_version_locations + self.messaging_opts = messaging_opts + + if not os.access(dir, os.F_OK): + raise util.CommandError( + "Path doesn't exist: %r. Please use " + "the 'init' command to create a new " + "scripts folder." % os.path.abspath(dir) + ) + + @property + def versions(self) -> str: + loc = self._version_locations + if len(loc) > 1: + raise util.CommandError("Multiple version_locations present") + else: + return loc[0] + + @util.memoized_property + def _version_locations(self) -> Sequence[str]: + if self.version_locations: + return [ + os.path.abspath(util.coerce_resource_to_filename(location)) + for location in self.version_locations + ] + else: + return (os.path.abspath(os.path.join(self.dir, "versions")),) + + def _load_revisions(self) -> Iterator[Script]: + if self.version_locations: + paths = [ + vers + for vers in self._version_locations + if os.path.exists(vers) + ] + else: + paths = [self.versions] + + dupes = set() + for vers in paths: + for file_path in Script._list_py_dir(self, vers): + real_path = os.path.realpath(file_path) + if real_path in dupes: + util.warn( + "File %s loaded twice! ignoring. Please ensure " + "version_locations is unique." % real_path + ) + continue + dupes.add(real_path) + + filename = os.path.basename(real_path) + dir_name = os.path.dirname(real_path) + script = Script._from_filename(self, dir_name, filename) + if script is None: + continue + yield script + + @classmethod + def from_config(cls, config: Config) -> ScriptDirectory: + """Produce a new :class:`.ScriptDirectory` given a :class:`.Config` + instance. + + The :class:`.Config` need only have the ``script_location`` key + present. + + """ + script_location = config.get_main_option("script_location") + if script_location is None: + raise util.CommandError( + "No 'script_location' key " "found in configuration." + ) + truncate_slug_length: Optional[int] + tsl = config.get_main_option("truncate_slug_length") + if tsl is not None: + truncate_slug_length = int(tsl) + else: + truncate_slug_length = None + + version_locations_str = config.get_main_option("version_locations") + version_locations: Optional[List[str]] + if version_locations_str: + version_path_separator = config.get_main_option( + "version_path_separator" + ) + + split_on_path = { + None: None, + "space": " ", + "os": os.pathsep, + ":": ":", + ";": ";", + } + + try: + split_char: Optional[str] = split_on_path[ + version_path_separator + ] + except KeyError as ke: + raise ValueError( + "'%s' is not a valid value for " + "version_path_separator; " + "expected 'space', 'os', ':', ';'" % version_path_separator + ) from ke + else: + if split_char is None: + # legacy behaviour for backwards compatibility + version_locations = _split_on_space_comma.split( + version_locations_str + ) + else: + version_locations = [ + x for x in version_locations_str.split(split_char) if x + ] + else: + version_locations = None + + prepend_sys_path = config.get_main_option("prepend_sys_path") + if prepend_sys_path: + sys.path[:0] = list( + _split_on_space_comma_colon.split(prepend_sys_path) + ) + + rvl = config.get_main_option("recursive_version_locations") == "true" + return ScriptDirectory( + util.coerce_resource_to_filename(script_location), + file_template=config.get_main_option( + "file_template", _default_file_template + ), + truncate_slug_length=truncate_slug_length, + sourceless=config.get_main_option("sourceless") == "true", + output_encoding=config.get_main_option("output_encoding", "utf-8"), + version_locations=version_locations, + timezone=config.get_main_option("timezone"), + hook_config=config.get_section("post_write_hooks", {}), + recursive_version_locations=rvl, + messaging_opts=config.messaging_opts, + ) + + @contextmanager + def _catch_revision_errors( + self, + ancestor: Optional[str] = None, + multiple_heads: Optional[str] = None, + start: Optional[str] = None, + end: Optional[str] = None, + resolution: Optional[str] = None, + ) -> Iterator[None]: + try: + yield + except revision.RangeNotAncestorError as rna: + if start is None: + start = cast(Any, rna.lower) + if end is None: + end = cast(Any, rna.upper) + if not ancestor: + ancestor = ( + "Requested range %(start)s:%(end)s does not refer to " + "ancestor/descendant revisions along the same branch" + ) + ancestor = ancestor % {"start": start, "end": end} + raise util.CommandError(ancestor) from rna + except revision.MultipleHeads as mh: + if not multiple_heads: + multiple_heads = ( + "Multiple head revisions are present for given " + "argument '%(head_arg)s'; please " + "specify a specific target revision, " + "'@%(head_arg)s' to " + "narrow to a specific head, or 'heads' for all heads" + ) + multiple_heads = multiple_heads % { + "head_arg": end or mh.argument, + "heads": util.format_as_comma(mh.heads), + } + raise util.CommandError(multiple_heads) from mh + except revision.ResolutionError as re: + if resolution is None: + resolution = "Can't locate revision identified by '%s'" % ( + re.argument + ) + raise util.CommandError(resolution) from re + except revision.RevisionError as err: + raise util.CommandError(err.args[0]) from err + + def walk_revisions( + self, base: str = "base", head: str = "heads" + ) -> Iterator[Script]: + """Iterate through all revisions. + + :param base: the base revision, or "base" to start from the + empty revision. + + :param head: the head revision; defaults to "heads" to indicate + all head revisions. May also be "head" to indicate a single + head revision. + + """ + with self._catch_revision_errors(start=base, end=head): + for rev in self.revision_map.iterate_revisions( + head, base, inclusive=True, assert_relative_length=False + ): + yield cast(Script, rev) + + def get_revisions(self, id_: _GetRevArg) -> Tuple[Script, ...]: + """Return the :class:`.Script` instance with the given rev identifier, + symbolic name, or sequence of identifiers. + + """ + with self._catch_revision_errors(): + return cast( + Tuple[Script, ...], + self.revision_map.get_revisions(id_), + ) + + def get_all_current(self, id_: Tuple[str, ...]) -> Set[Script]: + with self._catch_revision_errors(): + return cast(Set[Script], self.revision_map._get_all_current(id_)) + + def get_revision(self, id_: str) -> Script: + """Return the :class:`.Script` instance with the given rev id. + + .. seealso:: + + :meth:`.ScriptDirectory.get_revisions` + + """ + + with self._catch_revision_errors(): + return cast(Script, self.revision_map.get_revision(id_)) + + def as_revision_number( + self, id_: Optional[str] + ) -> Optional[Union[str, Tuple[str, ...]]]: + """Convert a symbolic revision, i.e. 'head' or 'base', into + an actual revision number.""" + + with self._catch_revision_errors(): + rev, branch_name = self.revision_map._resolve_revision_number(id_) + + if not rev: + # convert () to None + return None + elif id_ == "heads": + return rev + else: + return rev[0] + + def iterate_revisions( + self, + upper: Union[str, Tuple[str, ...], None], + lower: Union[str, Tuple[str, ...], None], + **kw: Any, + ) -> Iterator[Script]: + """Iterate through script revisions, starting at the given + upper revision identifier and ending at the lower. + + The traversal uses strictly the `down_revision` + marker inside each migration script, so + it is a requirement that upper >= lower, + else you'll get nothing back. + + The iterator yields :class:`.Script` objects. + + .. seealso:: + + :meth:`.RevisionMap.iterate_revisions` + + """ + return cast( + Iterator[Script], + self.revision_map.iterate_revisions(upper, lower, **kw), + ) + + def get_current_head(self) -> Optional[str]: + """Return the current head revision. + + If the script directory has multiple heads + due to branching, an error is raised; + :meth:`.ScriptDirectory.get_heads` should be + preferred. + + :return: a string revision number. + + .. seealso:: + + :meth:`.ScriptDirectory.get_heads` + + """ + with self._catch_revision_errors( + multiple_heads=( + "The script directory has multiple heads (due to branching)." + "Please use get_heads(), or merge the branches using " + "alembic merge." + ) + ): + return self.revision_map.get_current_head() + + def get_heads(self) -> List[str]: + """Return all "versioned head" revisions as strings. + + This is normally a list of length one, + unless branches are present. The + :meth:`.ScriptDirectory.get_current_head()` method + can be used normally when a script directory + has only one head. + + :return: a tuple of string revision numbers. + """ + return list(self.revision_map.heads) + + def get_base(self) -> Optional[str]: + """Return the "base" revision as a string. + + This is the revision number of the script that + has a ``down_revision`` of None. + + If the script directory has multiple bases, an error is raised; + :meth:`.ScriptDirectory.get_bases` should be + preferred. + + """ + bases = self.get_bases() + if len(bases) > 1: + raise util.CommandError( + "The script directory has multiple bases. " + "Please use get_bases()." + ) + elif bases: + return bases[0] + else: + return None + + def get_bases(self) -> List[str]: + """return all "base" revisions as strings. + + This is the revision number of all scripts that + have a ``down_revision`` of None. + + """ + return list(self.revision_map.bases) + + def _upgrade_revs( + self, destination: str, current_rev: str + ) -> List[RevisionStep]: + with self._catch_revision_errors( + ancestor="Destination %(end)s is not a valid upgrade " + "target from current head(s)", + end=destination, + ): + revs = self.iterate_revisions( + destination, current_rev, implicit_base=True + ) + return [ + migration.MigrationStep.upgrade_from_script( + self.revision_map, script + ) + for script in reversed(list(revs)) + ] + + def _downgrade_revs( + self, destination: str, current_rev: Optional[str] + ) -> List[RevisionStep]: + with self._catch_revision_errors( + ancestor="Destination %(end)s is not a valid downgrade " + "target from current head(s)", + end=destination, + ): + revs = self.iterate_revisions( + current_rev, destination, select_for_downgrade=True + ) + return [ + migration.MigrationStep.downgrade_from_script( + self.revision_map, script + ) + for script in revs + ] + + def _stamp_revs( + self, revision: _RevIdType, heads: _RevIdType + ) -> List[StampStep]: + with self._catch_revision_errors( + multiple_heads="Multiple heads are present; please specify a " + "single target revision" + ): + heads_revs = self.get_revisions(heads) + + steps = [] + + if not revision: + revision = "base" + + filtered_heads: List[Script] = [] + for rev in util.to_tuple(revision): + if rev: + filtered_heads.extend( + self.revision_map.filter_for_lineage( + cast(Sequence[Script], heads_revs), + rev, + include_dependencies=True, + ) + ) + filtered_heads = util.unique_list(filtered_heads) + + dests = self.get_revisions(revision) or [None] + + for dest in dests: + if dest is None: + # dest is 'base'. Return a "delete branch" migration + # for all applicable heads. + steps.extend( + [ + migration.StampStep( + head.revision, + None, + False, + True, + self.revision_map, + ) + for head in filtered_heads + ] + ) + continue + elif dest in filtered_heads: + # the dest is already in the version table, do nothing. + continue + + # figure out if the dest is a descendant or an + # ancestor of the selected nodes + descendants = set( + self.revision_map._get_descendant_nodes([dest]) + ) + ancestors = set(self.revision_map._get_ancestor_nodes([dest])) + + if descendants.intersection(filtered_heads): + # heads are above the target, so this is a downgrade. + # we can treat them as a "merge", single step. + assert not ancestors.intersection(filtered_heads) + todo_heads = [head.revision for head in filtered_heads] + step = migration.StampStep( + todo_heads, + dest.revision, + False, + False, + self.revision_map, + ) + steps.append(step) + continue + elif ancestors.intersection(filtered_heads): + # heads are below the target, so this is an upgrade. + # we can treat them as a "merge", single step. + todo_heads = [head.revision for head in filtered_heads] + step = migration.StampStep( + todo_heads, + dest.revision, + True, + False, + self.revision_map, + ) + steps.append(step) + continue + else: + # destination is in a branch not represented, + # treat it as new branch + step = migration.StampStep( + (), dest.revision, True, True, self.revision_map + ) + steps.append(step) + continue + + return steps + + def run_env(self) -> None: + """Run the script environment. + + This basically runs the ``env.py`` script present + in the migration environment. It is called exclusively + by the command functions in :mod:`alembic.command`. + + + """ + util.load_python_file(self.dir, "env.py") + + @property + def env_py_location(self) -> str: + return os.path.abspath(os.path.join(self.dir, "env.py")) + + def _generate_template(self, src: str, dest: str, **kw: Any) -> None: + with util.status( + f"Generating {os.path.abspath(dest)}", **self.messaging_opts + ): + util.template_to_file(src, dest, self.output_encoding, **kw) + + def _copy_file(self, src: str, dest: str) -> None: + with util.status( + f"Generating {os.path.abspath(dest)}", **self.messaging_opts + ): + shutil.copy(src, dest) + + def _ensure_directory(self, path: str) -> None: + path = os.path.abspath(path) + if not os.path.exists(path): + with util.status( + f"Creating directory {path}", **self.messaging_opts + ): + os.makedirs(path) + + def _generate_create_date(self) -> datetime.datetime: + if self.timezone is not None: + if ZoneInfo is None: + raise util.CommandError( + "Python >= 3.9 is required for timezone support or" + "the 'backports.zoneinfo' package must be installed." + ) + # First, assume correct capitalization + try: + tzinfo = ZoneInfo(self.timezone) + except ZoneInfoNotFoundError: + tzinfo = None + if tzinfo is None: + try: + tzinfo = ZoneInfo(self.timezone.upper()) + except ZoneInfoNotFoundError: + raise util.CommandError( + "Can't locate timezone: %s" % self.timezone + ) from None + create_date = ( + datetime.datetime.utcnow() + .replace(tzinfo=datetime.timezone.utc) + .astimezone(tzinfo) + ) + else: + create_date = datetime.datetime.now() + return create_date + + def generate_revision( + self, + revid: str, + message: Optional[str], + head: Optional[_RevIdType] = None, + splice: Optional[bool] = False, + branch_labels: Optional[_RevIdType] = None, + version_path: Optional[str] = None, + depends_on: Optional[_RevIdType] = None, + **kw: Any, + ) -> Optional[Script]: + """Generate a new revision file. + + This runs the ``script.py.mako`` template, given + template arguments, and creates a new file. + + :param revid: String revision id. Typically this + comes from ``alembic.util.rev_id()``. + :param message: the revision message, the one passed + by the -m argument to the ``revision`` command. + :param head: the head revision to generate against. Defaults + to the current "head" if no branches are present, else raises + an exception. + :param splice: if True, allow the "head" version to not be an + actual head; otherwise, the selected head must be a head + (e.g. endpoint) revision. + + """ + if head is None: + head = "head" + + try: + Script.verify_rev_id(revid) + except revision.RevisionError as err: + raise util.CommandError(err.args[0]) from err + + with self._catch_revision_errors( + multiple_heads=( + "Multiple heads are present; please specify the head " + "revision on which the new revision should be based, " + "or perform a merge." + ) + ): + heads = cast( + Tuple[Optional["Revision"], ...], + self.revision_map.get_revisions(head), + ) + for h in heads: + assert h != "base" # type: ignore[comparison-overlap] + + if len(set(heads)) != len(heads): + raise util.CommandError("Duplicate head revisions specified") + + create_date = self._generate_create_date() + + if version_path is None: + if len(self._version_locations) > 1: + for head_ in heads: + if head_ is not None: + assert isinstance(head_, Script) + version_path = os.path.dirname(head_.path) + break + else: + raise util.CommandError( + "Multiple version locations present, " + "please specify --version-path" + ) + else: + version_path = self.versions + + norm_path = os.path.normpath(os.path.abspath(version_path)) + for vers_path in self._version_locations: + if os.path.normpath(vers_path) == norm_path: + break + else: + raise util.CommandError( + "Path %s is not represented in current " + "version locations" % version_path + ) + + if self.version_locations: + self._ensure_directory(version_path) + + path = self._rev_path(version_path, revid, message, create_date) + + if not splice: + for head_ in heads: + if head_ is not None and not head_.is_head: + raise util.CommandError( + "Revision %s is not a head revision; please specify " + "--splice to create a new branch from this revision" + % head_.revision + ) + + resolved_depends_on: Optional[List[str]] + if depends_on: + with self._catch_revision_errors(): + resolved_depends_on = [ + dep + if dep in rev.branch_labels # maintain branch labels + else rev.revision # resolve partial revision identifiers + for rev, dep in [ + (not_none(self.revision_map.get_revision(dep)), dep) + for dep in util.to_list(depends_on) + ] + ] + else: + resolved_depends_on = None + + self._generate_template( + os.path.join(self.dir, "script.py.mako"), + path, + up_revision=str(revid), + down_revision=revision.tuple_rev_as_scalar( + tuple(h.revision if h is not None else None for h in heads) + ), + branch_labels=util.to_tuple(branch_labels), + depends_on=revision.tuple_rev_as_scalar(resolved_depends_on), + create_date=create_date, + comma=util.format_as_comma, + message=message if message is not None else ("empty message"), + **kw, + ) + + post_write_hooks = self.hook_config + if post_write_hooks: + write_hooks._run_hooks(path, post_write_hooks) + + try: + script = Script._from_path(self, path) + except revision.RevisionError as err: + raise util.CommandError(err.args[0]) from err + if script is None: + return None + if branch_labels and not script.branch_labels: + raise util.CommandError( + "Version %s specified branch_labels %s, however the " + "migration file %s does not have them; have you upgraded " + "your script.py.mako to include the " + "'branch_labels' section?" + % (script.revision, branch_labels, script.path) + ) + self.revision_map.add_revision(script) + return script + + def _rev_path( + self, + path: str, + rev_id: str, + message: Optional[str], + create_date: datetime.datetime, + ) -> str: + epoch = int(create_date.timestamp()) + slug = "_".join(_slug_re.findall(message or "")).lower() + if len(slug) > self.truncate_slug_length: + slug = slug[: self.truncate_slug_length].rsplit("_", 1)[0] + "_" + filename = "%s.py" % ( + self.file_template + % { + "rev": rev_id, + "slug": slug, + "epoch": epoch, + "year": create_date.year, + "month": create_date.month, + "day": create_date.day, + "hour": create_date.hour, + "minute": create_date.minute, + "second": create_date.second, + } + ) + return os.path.join(path, filename) + + +class Script(revision.Revision): + + """Represent a single revision file in a ``versions/`` directory. + + The :class:`.Script` instance is returned by methods + such as :meth:`.ScriptDirectory.iterate_revisions`. + + """ + + def __init__(self, module: ModuleType, rev_id: str, path: str): + self.module = module + self.path = path + super().__init__( + rev_id, + module.down_revision, + branch_labels=util.to_tuple( + getattr(module, "branch_labels", None), default=() + ), + dependencies=util.to_tuple( + getattr(module, "depends_on", None), default=() + ), + ) + + module: ModuleType + """The Python module representing the actual script itself.""" + + path: str + """Filesystem path of the script.""" + + _db_current_indicator: Optional[bool] = None + """Utility variable which when set will cause string output to indicate + this is a "current" version in some database""" + + @property + def doc(self) -> str: + """Return the docstring given in the script.""" + + return re.split("\n\n", self.longdoc)[0] + + @property + def longdoc(self) -> str: + """Return the docstring given in the script.""" + + doc = self.module.__doc__ + if doc: + if hasattr(self.module, "_alembic_source_encoding"): + doc = doc.decode( # type: ignore[attr-defined] + self.module._alembic_source_encoding + ) + return doc.strip() # type: ignore[union-attr] + else: + return "" + + @property + def log_entry(self) -> str: + entry = "Rev: %s%s%s%s%s\n" % ( + self.revision, + " (head)" if self.is_head else "", + " (branchpoint)" if self.is_branch_point else "", + " (mergepoint)" if self.is_merge_point else "", + " (current)" if self._db_current_indicator else "", + ) + if self.is_merge_point: + entry += "Merges: %s\n" % (self._format_down_revision(),) + else: + entry += "Parent: %s\n" % (self._format_down_revision(),) + + if self.dependencies: + entry += "Also depends on: %s\n" % ( + util.format_as_comma(self.dependencies) + ) + + if self.is_branch_point: + entry += "Branches into: %s\n" % ( + util.format_as_comma(self.nextrev) + ) + + if self.branch_labels: + entry += "Branch names: %s\n" % ( + util.format_as_comma(self.branch_labels), + ) + + entry += "Path: %s\n" % (self.path,) + + entry += "\n%s\n" % ( + "\n".join(" %s" % para for para in self.longdoc.splitlines()) + ) + return entry + + def __str__(self) -> str: + return "%s -> %s%s%s%s, %s" % ( + self._format_down_revision(), + self.revision, + " (head)" if self.is_head else "", + " (branchpoint)" if self.is_branch_point else "", + " (mergepoint)" if self.is_merge_point else "", + self.doc, + ) + + def _head_only( + self, + include_branches: bool = False, + include_doc: bool = False, + include_parents: bool = False, + tree_indicators: bool = True, + head_indicators: bool = True, + ) -> str: + text = self.revision + if include_parents: + if self.dependencies: + text = "%s (%s) -> %s" % ( + self._format_down_revision(), + util.format_as_comma(self.dependencies), + text, + ) + else: + text = "%s -> %s" % (self._format_down_revision(), text) + assert text is not None + if include_branches and self.branch_labels: + text += " (%s)" % util.format_as_comma(self.branch_labels) + if head_indicators or tree_indicators: + text += "%s%s%s" % ( + " (head)" if self._is_real_head else "", + " (effective head)" + if self.is_head and not self._is_real_head + else "", + " (current)" if self._db_current_indicator else "", + ) + if tree_indicators: + text += "%s%s" % ( + " (branchpoint)" if self.is_branch_point else "", + " (mergepoint)" if self.is_merge_point else "", + ) + if include_doc: + text += ", %s" % self.doc + return text + + def cmd_format( + self, + verbose: bool, + include_branches: bool = False, + include_doc: bool = False, + include_parents: bool = False, + tree_indicators: bool = True, + ) -> str: + if verbose: + return self.log_entry + else: + return self._head_only( + include_branches, include_doc, include_parents, tree_indicators + ) + + def _format_down_revision(self) -> str: + if not self.down_revision: + return "" + else: + return util.format_as_comma(self._versioned_down_revisions) + + @classmethod + def _from_path( + cls, scriptdir: ScriptDirectory, path: str + ) -> Optional[Script]: + dir_, filename = os.path.split(path) + return cls._from_filename(scriptdir, dir_, filename) + + @classmethod + def _list_py_dir(cls, scriptdir: ScriptDirectory, path: str) -> List[str]: + paths = [] + for root, dirs, files in os.walk(path, topdown=True): + if root.endswith("__pycache__"): + # a special case - we may include these files + # if a `sourceless` option is specified + continue + + for filename in sorted(files): + paths.append(os.path.join(root, filename)) + + if scriptdir.sourceless: + # look for __pycache__ + py_cache_path = os.path.join(root, "__pycache__") + if os.path.exists(py_cache_path): + # add all files from __pycache__ whose filename is not + # already in the names we got from the version directory. + # add as relative paths including __pycache__ token + names = {filename.split(".")[0] for filename in files} + paths.extend( + os.path.join(py_cache_path, pyc) + for pyc in os.listdir(py_cache_path) + if pyc.split(".")[0] not in names + ) + + if not scriptdir.recursive_version_locations: + break + + # the real script order is defined by revision, + # but it may be undefined if there are many files with a same + # `down_revision`, for a better user experience (ex. debugging), + # we use a deterministic order + dirs.sort() + + return paths + + @classmethod + def _from_filename( + cls, scriptdir: ScriptDirectory, dir_: str, filename: str + ) -> Optional[Script]: + if scriptdir.sourceless: + py_match = _sourceless_rev_file.match(filename) + else: + py_match = _only_source_rev_file.match(filename) + + if not py_match: + return None + + py_filename = py_match.group(1) + + if scriptdir.sourceless: + is_c = py_match.group(2) == "c" + is_o = py_match.group(2) == "o" + else: + is_c = is_o = False + + if is_o or is_c: + py_exists = os.path.exists(os.path.join(dir_, py_filename)) + pyc_exists = os.path.exists(os.path.join(dir_, py_filename + "c")) + + # prefer .py over .pyc because we'd like to get the + # source encoding; prefer .pyc over .pyo because we'd like to + # have the docstrings which a -OO file would not have + if py_exists or is_o and pyc_exists: + return None + + module = util.load_python_file(dir_, filename) + + if not hasattr(module, "revision"): + # attempt to get the revision id from the script name, + # this for legacy only + m = _legacy_rev.match(filename) + if not m: + raise util.CommandError( + "Could not determine revision id from filename %s. " + "Be sure the 'revision' variable is " + "declared inside the script (please see 'Upgrading " + "from Alembic 0.1 to 0.2' in the documentation)." + % filename + ) + else: + revision = m.group(1) + else: + revision = module.revision + return Script(module, revision, os.path.join(dir_, filename)) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/revision.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/revision.py new file mode 100644 index 0000000000000000000000000000000000000000..77a802cdcadf9c59049fdb5db1c2be95d305a1ae --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/revision.py @@ -0,0 +1,1721 @@ +from __future__ import annotations + +import collections +import re +from typing import Any +from typing import Callable +from typing import cast +from typing import Collection +from typing import Deque +from typing import Dict +from typing import FrozenSet +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Optional +from typing import overload +from typing import Protocol +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from sqlalchemy import util as sqlautil + +from .. import util +from ..util import not_none + +if TYPE_CHECKING: + from typing import Literal + +_RevIdType = Union[str, List[str], Tuple[str, ...]] +_GetRevArg = Union[ + str, + Iterable[Optional[str]], + Iterable[str], +] +_RevisionIdentifierType = Union[str, Tuple[str, ...], None] +_RevisionOrStr = Union["Revision", str] +_RevisionOrBase = Union["Revision", "Literal['base']"] +_InterimRevisionMapType = Dict[str, "Revision"] +_RevisionMapType = Dict[Union[None, str, Tuple[()]], Optional["Revision"]] +_T = TypeVar("_T") +_TR = TypeVar("_TR", bound=Optional[_RevisionOrStr]) + +_relative_destination = re.compile(r"(?:(.+?)@)?(\w+)?((?:\+|-)\d+)") +_revision_illegal_chars = ["@", "-", "+"] + + +class _CollectRevisionsProtocol(Protocol): + def __call__( + self, + upper: _RevisionIdentifierType, + lower: _RevisionIdentifierType, + inclusive: bool, + implicit_base: bool, + assert_relative_length: bool, + ) -> Tuple[Set[Revision], Tuple[Optional[_RevisionOrBase], ...]]: + ... + + +class RevisionError(Exception): + pass + + +class RangeNotAncestorError(RevisionError): + def __init__( + self, lower: _RevisionIdentifierType, upper: _RevisionIdentifierType + ) -> None: + self.lower = lower + self.upper = upper + super().__init__( + "Revision %s is not an ancestor of revision %s" + % (lower or "base", upper or "base") + ) + + +class MultipleHeads(RevisionError): + def __init__(self, heads: Sequence[str], argument: Optional[str]) -> None: + self.heads = heads + self.argument = argument + super().__init__( + "Multiple heads are present for given argument '%s'; " + "%s" % (argument, ", ".join(heads)) + ) + + +class ResolutionError(RevisionError): + def __init__(self, message: str, argument: str) -> None: + super().__init__(message) + self.argument = argument + + +class CycleDetected(RevisionError): + kind = "Cycle" + + def __init__(self, revisions: Sequence[str]) -> None: + self.revisions = revisions + super().__init__( + "%s is detected in revisions (%s)" + % (self.kind, ", ".join(revisions)) + ) + + +class DependencyCycleDetected(CycleDetected): + kind = "Dependency cycle" + + def __init__(self, revisions: Sequence[str]) -> None: + super().__init__(revisions) + + +class LoopDetected(CycleDetected): + kind = "Self-loop" + + def __init__(self, revision: str) -> None: + super().__init__([revision]) + + +class DependencyLoopDetected(DependencyCycleDetected, LoopDetected): + kind = "Dependency self-loop" + + def __init__(self, revision: Sequence[str]) -> None: + super().__init__(revision) + + +class RevisionMap: + """Maintains a map of :class:`.Revision` objects. + + :class:`.RevisionMap` is used by :class:`.ScriptDirectory` to maintain + and traverse the collection of :class:`.Script` objects, which are + themselves instances of :class:`.Revision`. + + """ + + def __init__(self, generator: Callable[[], Iterable[Revision]]) -> None: + """Construct a new :class:`.RevisionMap`. + + :param generator: a zero-arg callable that will generate an iterable + of :class:`.Revision` instances to be used. These are typically + :class:`.Script` subclasses within regular Alembic use. + + """ + self._generator = generator + + @util.memoized_property + def heads(self) -> Tuple[str, ...]: + """All "head" revisions as strings. + + This is normally a tuple of length one, + unless unmerged branches are present. + + :return: a tuple of string revision numbers. + + """ + self._revision_map + return self.heads + + @util.memoized_property + def bases(self) -> Tuple[str, ...]: + """All "base" revisions as strings. + + These are revisions that have a ``down_revision`` of None, + or empty tuple. + + :return: a tuple of string revision numbers. + + """ + self._revision_map + return self.bases + + @util.memoized_property + def _real_heads(self) -> Tuple[str, ...]: + """All "real" head revisions as strings. + + :return: a tuple of string revision numbers. + + """ + self._revision_map + return self._real_heads + + @util.memoized_property + def _real_bases(self) -> Tuple[str, ...]: + """All "real" base revisions as strings. + + :return: a tuple of string revision numbers. + + """ + self._revision_map + return self._real_bases + + @util.memoized_property + def _revision_map(self) -> _RevisionMapType: + """memoized attribute, initializes the revision map from the + initial collection. + + """ + # Ordering required for some tests to pass (but not required in + # general) + map_: _InterimRevisionMapType = sqlautil.OrderedDict() + + heads: Set[Revision] = sqlautil.OrderedSet() + _real_heads: Set[Revision] = sqlautil.OrderedSet() + bases: Tuple[Revision, ...] = () + _real_bases: Tuple[Revision, ...] = () + + has_branch_labels = set() + all_revisions = set() + + for revision in self._generator(): + all_revisions.add(revision) + + if revision.revision in map_: + util.warn( + "Revision %s is present more than once" % revision.revision + ) + map_[revision.revision] = revision + if revision.branch_labels: + has_branch_labels.add(revision) + + heads.add(revision) + _real_heads.add(revision) + if revision.is_base: + bases += (revision,) + if revision._is_real_base: + _real_bases += (revision,) + + # add the branch_labels to the map_. We'll need these + # to resolve the dependencies. + rev_map = map_.copy() + self._map_branch_labels( + has_branch_labels, cast(_RevisionMapType, map_) + ) + + # resolve dependency names from branch labels and symbolic + # names + self._add_depends_on(all_revisions, cast(_RevisionMapType, map_)) + + for rev in map_.values(): + for downrev in rev._all_down_revisions: + if downrev not in map_: + util.warn( + "Revision %s referenced from %s is not present" + % (downrev, rev) + ) + down_revision = map_[downrev] + down_revision.add_nextrev(rev) + if downrev in rev._versioned_down_revisions: + heads.discard(down_revision) + _real_heads.discard(down_revision) + + # once the map has downrevisions populated, the dependencies + # can be further refined to include only those which are not + # already ancestors + self._normalize_depends_on(all_revisions, cast(_RevisionMapType, map_)) + self._detect_cycles(rev_map, heads, bases, _real_heads, _real_bases) + + revision_map: _RevisionMapType = dict(map_.items()) + revision_map[None] = revision_map[()] = None + self.heads = tuple(rev.revision for rev in heads) + self._real_heads = tuple(rev.revision for rev in _real_heads) + self.bases = tuple(rev.revision for rev in bases) + self._real_bases = tuple(rev.revision for rev in _real_bases) + + self._add_branches(has_branch_labels, revision_map) + return revision_map + + def _detect_cycles( + self, + rev_map: _InterimRevisionMapType, + heads: Set[Revision], + bases: Tuple[Revision, ...], + _real_heads: Set[Revision], + _real_bases: Tuple[Revision, ...], + ) -> None: + if not rev_map: + return + if not heads or not bases: + raise CycleDetected(list(rev_map)) + total_space = { + rev.revision + for rev in self._iterate_related_revisions( + lambda r: r._versioned_down_revisions, + heads, + map_=cast(_RevisionMapType, rev_map), + ) + }.intersection( + rev.revision + for rev in self._iterate_related_revisions( + lambda r: r.nextrev, + bases, + map_=cast(_RevisionMapType, rev_map), + ) + ) + deleted_revs = set(rev_map.keys()) - total_space + if deleted_revs: + raise CycleDetected(sorted(deleted_revs)) + + if not _real_heads or not _real_bases: + raise DependencyCycleDetected(list(rev_map)) + total_space = { + rev.revision + for rev in self._iterate_related_revisions( + lambda r: r._all_down_revisions, + _real_heads, + map_=cast(_RevisionMapType, rev_map), + ) + }.intersection( + rev.revision + for rev in self._iterate_related_revisions( + lambda r: r._all_nextrev, + _real_bases, + map_=cast(_RevisionMapType, rev_map), + ) + ) + deleted_revs = set(rev_map.keys()) - total_space + if deleted_revs: + raise DependencyCycleDetected(sorted(deleted_revs)) + + def _map_branch_labels( + self, revisions: Collection[Revision], map_: _RevisionMapType + ) -> None: + for revision in revisions: + if revision.branch_labels: + assert revision._orig_branch_labels is not None + for branch_label in revision._orig_branch_labels: + if branch_label in map_: + map_rev = map_[branch_label] + assert map_rev is not None + raise RevisionError( + "Branch name '%s' in revision %s already " + "used by revision %s" + % ( + branch_label, + revision.revision, + map_rev.revision, + ) + ) + map_[branch_label] = revision + + def _add_branches( + self, revisions: Collection[Revision], map_: _RevisionMapType + ) -> None: + for revision in revisions: + if revision.branch_labels: + revision.branch_labels.update(revision.branch_labels) + for node in self._get_descendant_nodes( + [revision], map_, include_dependencies=False + ): + node.branch_labels.update(revision.branch_labels) + + parent = node + while ( + parent + and not parent._is_real_branch_point + and not parent.is_merge_point + ): + parent.branch_labels.update(revision.branch_labels) + if parent.down_revision: + parent = map_[parent.down_revision] + else: + break + + def _add_depends_on( + self, revisions: Collection[Revision], map_: _RevisionMapType + ) -> None: + """Resolve the 'dependencies' for each revision in a collection + in terms of actual revision ids, as opposed to branch labels or other + symbolic names. + + The collection is then assigned to the _resolved_dependencies + attribute on each revision object. + + """ + + for revision in revisions: + if revision.dependencies: + deps = [ + map_[dep] for dep in util.to_tuple(revision.dependencies) + ] + revision._resolved_dependencies = tuple( + [d.revision for d in deps if d is not None] + ) + else: + revision._resolved_dependencies = () + + def _normalize_depends_on( + self, revisions: Collection[Revision], map_: _RevisionMapType + ) -> None: + """Create a collection of "dependencies" that omits dependencies + that are already ancestor nodes for each revision in a given + collection. + + This builds upon the _resolved_dependencies collection created in the + _add_depends_on() method, looking in the fully populated revision map + for ancestors, and omitting them as the _resolved_dependencies + collection as it is copied to a new collection. The new collection is + then assigned to the _normalized_resolved_dependencies attribute on + each revision object. + + The collection is then used to determine the immediate "down revision" + identifiers for this revision. + + """ + + for revision in revisions: + if revision._resolved_dependencies: + normalized_resolved = set(revision._resolved_dependencies) + for rev in self._get_ancestor_nodes( + [revision], + include_dependencies=False, + map_=map_, + ): + if rev is revision: + continue + elif rev._resolved_dependencies: + normalized_resolved.difference_update( + rev._resolved_dependencies + ) + + revision._normalized_resolved_dependencies = tuple( + normalized_resolved + ) + else: + revision._normalized_resolved_dependencies = () + + def add_revision(self, revision: Revision, _replace: bool = False) -> None: + """add a single revision to an existing map. + + This method is for single-revision use cases, it's not + appropriate for fully populating an entire revision map. + + """ + map_ = self._revision_map + if not _replace and revision.revision in map_: + util.warn( + "Revision %s is present more than once" % revision.revision + ) + elif _replace and revision.revision not in map_: + raise Exception("revision %s not in map" % revision.revision) + + map_[revision.revision] = revision + + revisions = [revision] + self._add_branches(revisions, map_) + self._map_branch_labels(revisions, map_) + self._add_depends_on(revisions, map_) + + if revision.is_base: + self.bases += (revision.revision,) + if revision._is_real_base: + self._real_bases += (revision.revision,) + + for downrev in revision._all_down_revisions: + if downrev not in map_: + util.warn( + "Revision %s referenced from %s is not present" + % (downrev, revision) + ) + not_none(map_[downrev]).add_nextrev(revision) + + self._normalize_depends_on(revisions, map_) + + if revision._is_real_head: + self._real_heads = tuple( + head + for head in self._real_heads + if head + not in set(revision._all_down_revisions).union( + [revision.revision] + ) + ) + (revision.revision,) + if revision.is_head: + self.heads = tuple( + head + for head in self.heads + if head + not in set(revision._versioned_down_revisions).union( + [revision.revision] + ) + ) + (revision.revision,) + + def get_current_head( + self, branch_label: Optional[str] = None + ) -> Optional[str]: + """Return the current head revision. + + If the script directory has multiple heads + due to branching, an error is raised; + :meth:`.ScriptDirectory.get_heads` should be + preferred. + + :param branch_label: optional branch name which will limit the + heads considered to those which include that branch_label. + + :return: a string revision number. + + .. seealso:: + + :meth:`.ScriptDirectory.get_heads` + + """ + current_heads: Sequence[str] = self.heads + if branch_label: + current_heads = self.filter_for_lineage( + current_heads, branch_label + ) + if len(current_heads) > 1: + raise MultipleHeads( + current_heads, + "%s@head" % branch_label if branch_label else "head", + ) + + if current_heads: + return current_heads[0] + else: + return None + + def _get_base_revisions(self, identifier: str) -> Tuple[str, ...]: + return self.filter_for_lineage(self.bases, identifier) + + def get_revisions( + self, id_: Optional[_GetRevArg] + ) -> Tuple[Optional[_RevisionOrBase], ...]: + """Return the :class:`.Revision` instances with the given rev id + or identifiers. + + May be given a single identifier, a sequence of identifiers, or the + special symbols "head" or "base". The result is a tuple of one + or more identifiers, or an empty tuple in the case of "base". + + In the cases where 'head', 'heads' is requested and the + revision map is empty, returns an empty tuple. + + Supports partial identifiers, where the given identifier + is matched against all identifiers that start with the given + characters; if there is exactly one match, that determines the + full revision. + + """ + + if isinstance(id_, (list, tuple, set, frozenset)): + return sum([self.get_revisions(id_elem) for id_elem in id_], ()) + else: + resolved_id, branch_label = self._resolve_revision_number(id_) + if len(resolved_id) == 1: + try: + rint = int(resolved_id[0]) + if rint < 0: + # branch@-n -> walk down from heads + select_heads = self.get_revisions("heads") + if branch_label is not None: + select_heads = tuple( + head + for head in select_heads + if branch_label + in is_revision(head).branch_labels + ) + return tuple( + self._walk(head, steps=rint) + for head in select_heads + ) + except ValueError: + # couldn't resolve as integer + pass + return tuple( + self._revision_for_ident(rev_id, branch_label) + for rev_id in resolved_id + ) + + def get_revision(self, id_: Optional[str]) -> Optional[Revision]: + """Return the :class:`.Revision` instance with the given rev id. + + If a symbolic name such as "head" or "base" is given, resolves + the identifier into the current head or base revision. If the symbolic + name refers to multiples, :class:`.MultipleHeads` is raised. + + Supports partial identifiers, where the given identifier + is matched against all identifiers that start with the given + characters; if there is exactly one match, that determines the + full revision. + + """ + + resolved_id, branch_label = self._resolve_revision_number(id_) + if len(resolved_id) > 1: + raise MultipleHeads(resolved_id, id_) + + resolved: Union[str, Tuple[()]] = resolved_id[0] if resolved_id else () + return self._revision_for_ident(resolved, branch_label) + + def _resolve_branch(self, branch_label: str) -> Optional[Revision]: + try: + branch_rev = self._revision_map[branch_label] + except KeyError: + try: + nonbranch_rev = self._revision_for_ident(branch_label) + except ResolutionError as re: + raise ResolutionError( + "No such branch: '%s'" % branch_label, branch_label + ) from re + + else: + return nonbranch_rev + else: + return branch_rev + + def _revision_for_ident( + self, + resolved_id: Union[str, Tuple[()], None], + check_branch: Optional[str] = None, + ) -> Optional[Revision]: + branch_rev: Optional[Revision] + if check_branch: + branch_rev = self._resolve_branch(check_branch) + else: + branch_rev = None + + revision: Union[Optional[Revision], Literal[False]] + try: + revision = self._revision_map[resolved_id] + except KeyError: + # break out to avoid misleading py3k stack traces + revision = False + revs: Sequence[str] + if revision is False: + assert resolved_id + # do a partial lookup + revs = [ + x + for x in self._revision_map + if x and len(x) > 3 and x.startswith(resolved_id) + ] + + if branch_rev: + revs = self.filter_for_lineage(revs, check_branch) + if not revs: + raise ResolutionError( + "No such revision or branch '%s'%s" + % ( + resolved_id, + ( + "; please ensure at least four characters are " + "present for partial revision identifier matches" + if len(resolved_id) < 4 + else "" + ), + ), + resolved_id, + ) + elif len(revs) > 1: + raise ResolutionError( + "Multiple revisions start " + "with '%s': %s..." + % (resolved_id, ", ".join("'%s'" % r for r in revs[0:3])), + resolved_id, + ) + else: + revision = self._revision_map[revs[0]] + + if check_branch and revision is not None: + assert branch_rev is not None + assert resolved_id + if not self._shares_lineage( + revision.revision, branch_rev.revision + ): + raise ResolutionError( + "Revision %s is not a member of branch '%s'" + % (revision.revision, check_branch), + resolved_id, + ) + return revision + + def _filter_into_branch_heads( + self, targets: Iterable[Optional[_RevisionOrBase]] + ) -> Set[Optional[_RevisionOrBase]]: + targets = set(targets) + + for rev in list(targets): + assert rev + if targets.intersection( + self._get_descendant_nodes([rev], include_dependencies=False) + ).difference([rev]): + targets.discard(rev) + return targets + + def filter_for_lineage( + self, + targets: Iterable[_TR], + check_against: Optional[str], + include_dependencies: bool = False, + ) -> Tuple[_TR, ...]: + id_, branch_label = self._resolve_revision_number(check_against) + + shares = [] + if branch_label: + shares.append(branch_label) + if id_: + shares.extend(id_) + + return tuple( + tg + for tg in targets + if self._shares_lineage( + tg, shares, include_dependencies=include_dependencies + ) + ) + + def _shares_lineage( + self, + target: Optional[_RevisionOrStr], + test_against_revs: Sequence[_RevisionOrStr], + include_dependencies: bool = False, + ) -> bool: + if not test_against_revs: + return True + if not isinstance(target, Revision): + resolved_target = not_none(self._revision_for_ident(target)) + else: + resolved_target = target + + resolved_test_against_revs = [ + self._revision_for_ident(test_against_rev) + if not isinstance(test_against_rev, Revision) + else test_against_rev + for test_against_rev in util.to_tuple( + test_against_revs, default=() + ) + ] + + return bool( + set( + self._get_descendant_nodes( + [resolved_target], + include_dependencies=include_dependencies, + ) + ) + .union( + self._get_ancestor_nodes( + [resolved_target], + include_dependencies=include_dependencies, + ) + ) + .intersection(resolved_test_against_revs) + ) + + def _resolve_revision_number( + self, id_: Optional[_GetRevArg] + ) -> Tuple[Tuple[str, ...], Optional[str]]: + branch_label: Optional[str] + if isinstance(id_, str) and "@" in id_: + branch_label, id_ = id_.split("@", 1) + + elif id_ is not None and ( + (isinstance(id_, tuple) and id_ and not isinstance(id_[0], str)) + or not isinstance(id_, (str, tuple)) + ): + raise RevisionError( + "revision identifier %r is not a string; ensure database " + "driver settings are correct" % (id_,) + ) + + else: + branch_label = None + + # ensure map is loaded + self._revision_map + if id_ == "heads": + if branch_label: + return ( + self.filter_for_lineage(self.heads, branch_label), + branch_label, + ) + else: + return self._real_heads, branch_label + elif id_ == "head": + current_head = self.get_current_head(branch_label) + if current_head: + return (current_head,), branch_label + else: + return (), branch_label + elif id_ == "base" or id_ is None: + return (), branch_label + else: + return util.to_tuple(id_, default=None), branch_label + + def iterate_revisions( + self, + upper: _RevisionIdentifierType, + lower: _RevisionIdentifierType, + implicit_base: bool = False, + inclusive: bool = False, + assert_relative_length: bool = True, + select_for_downgrade: bool = False, + ) -> Iterator[Revision]: + """Iterate through script revisions, starting at the given + upper revision identifier and ending at the lower. + + The traversal uses strictly the `down_revision` + marker inside each migration script, so + it is a requirement that upper >= lower, + else you'll get nothing back. + + The iterator yields :class:`.Revision` objects. + + """ + fn: _CollectRevisionsProtocol + if select_for_downgrade: + fn = self._collect_downgrade_revisions + else: + fn = self._collect_upgrade_revisions + + revisions, heads = fn( + upper, + lower, + inclusive=inclusive, + implicit_base=implicit_base, + assert_relative_length=assert_relative_length, + ) + + for node in self._topological_sort(revisions, heads): + yield not_none(self.get_revision(node)) + + def _get_descendant_nodes( + self, + targets: Collection[Optional[_RevisionOrBase]], + map_: Optional[_RevisionMapType] = None, + check: bool = False, + omit_immediate_dependencies: bool = False, + include_dependencies: bool = True, + ) -> Iterator[Any]: + if omit_immediate_dependencies: + + def fn(rev: Revision) -> Iterable[str]: + if rev not in targets: + return rev._all_nextrev + else: + return rev.nextrev + + elif include_dependencies: + + def fn(rev: Revision) -> Iterable[str]: + return rev._all_nextrev + + else: + + def fn(rev: Revision) -> Iterable[str]: + return rev.nextrev + + return self._iterate_related_revisions( + fn, targets, map_=map_, check=check + ) + + def _get_ancestor_nodes( + self, + targets: Collection[Optional[_RevisionOrBase]], + map_: Optional[_RevisionMapType] = None, + check: bool = False, + include_dependencies: bool = True, + ) -> Iterator[Revision]: + if include_dependencies: + + def fn(rev: Revision) -> Iterable[str]: + return rev._normalized_down_revisions + + else: + + def fn(rev: Revision) -> Iterable[str]: + return rev._versioned_down_revisions + + return self._iterate_related_revisions( + fn, targets, map_=map_, check=check + ) + + def _iterate_related_revisions( + self, + fn: Callable[[Revision], Iterable[str]], + targets: Collection[Optional[_RevisionOrBase]], + map_: Optional[_RevisionMapType], + check: bool = False, + ) -> Iterator[Revision]: + if map_ is None: + map_ = self._revision_map + + seen = set() + todo: Deque[Revision] = collections.deque() + for target_for in targets: + target = is_revision(target_for) + todo.append(target) + if check: + per_target = set() + + while todo: + rev = todo.pop() + if check: + per_target.add(rev) + + if rev in seen: + continue + seen.add(rev) + # Check for map errors before collecting. + for rev_id in fn(rev): + next_rev = map_[rev_id] + assert next_rev is not None + if next_rev.revision != rev_id: + raise RevisionError( + "Dependency resolution failed; broken map" + ) + todo.append(next_rev) + yield rev + if check: + overlaps = per_target.intersection(targets).difference( + [target] + ) + if overlaps: + raise RevisionError( + "Requested revision %s overlaps with " + "other requested revisions %s" + % ( + target.revision, + ", ".join(r.revision for r in overlaps), + ) + ) + + def _topological_sort( + self, + revisions: Collection[Revision], + heads: Any, + ) -> List[str]: + """Yield revision ids of a collection of Revision objects in + topological sorted order (i.e. revisions always come after their + down_revisions and dependencies). Uses the order of keys in + _revision_map to sort. + + """ + + id_to_rev = self._revision_map + + def get_ancestors(rev_id: str) -> Set[str]: + return { + r.revision + for r in self._get_ancestor_nodes([id_to_rev[rev_id]]) + } + + todo = {d.revision for d in revisions} + + # Use revision map (ordered dict) key order to pre-sort. + inserted_order = list(self._revision_map) + + current_heads = list( + sorted( + {d.revision for d in heads if d.revision in todo}, + key=inserted_order.index, + ) + ) + ancestors_by_idx = [get_ancestors(rev_id) for rev_id in current_heads] + + output = [] + + current_candidate_idx = 0 + while current_heads: + candidate = current_heads[current_candidate_idx] + + for check_head_index, ancestors in enumerate(ancestors_by_idx): + # scan all the heads. see if we can continue walking + # down the current branch indicated by current_candidate_idx. + if ( + check_head_index != current_candidate_idx + and candidate in ancestors + ): + current_candidate_idx = check_head_index + # nope, another head is dependent on us, they have + # to be traversed first + break + else: + # yup, we can emit + if candidate in todo: + output.append(candidate) + todo.remove(candidate) + + # now update the heads with our ancestors. + + candidate_rev = id_to_rev[candidate] + assert candidate_rev is not None + + heads_to_add = [ + r + for r in candidate_rev._normalized_down_revisions + if r in todo and r not in current_heads + ] + + if not heads_to_add: + # no ancestors, so remove this head from the list + del current_heads[current_candidate_idx] + del ancestors_by_idx[current_candidate_idx] + current_candidate_idx = max(current_candidate_idx - 1, 0) + else: + if ( + not candidate_rev._normalized_resolved_dependencies + and len(candidate_rev._versioned_down_revisions) == 1 + ): + current_heads[current_candidate_idx] = heads_to_add[0] + + # for plain movement down a revision line without + # any mergepoints, branchpoints, or deps, we + # can update the ancestors collection directly + # by popping out the candidate we just emitted + ancestors_by_idx[current_candidate_idx].discard( + candidate + ) + + else: + # otherwise recalculate it again, things get + # complicated otherwise. This can possibly be + # improved to not run the whole ancestor thing + # each time but it was getting complicated + current_heads[current_candidate_idx] = heads_to_add[0] + current_heads.extend(heads_to_add[1:]) + ancestors_by_idx[ + current_candidate_idx + ] = get_ancestors(heads_to_add[0]) + ancestors_by_idx.extend( + get_ancestors(head) for head in heads_to_add[1:] + ) + + assert not todo + return output + + def _walk( + self, + start: Optional[Union[str, Revision]], + steps: int, + branch_label: Optional[str] = None, + no_overwalk: bool = True, + ) -> Optional[_RevisionOrBase]: + """ + Walk the requested number of :steps up (steps > 0) or down (steps < 0) + the revision tree. + + :branch_label is used to select branches only when walking up. + + If the walk goes past the boundaries of the tree and :no_overwalk is + True, None is returned, otherwise the walk terminates early. + + A RevisionError is raised if there is no unambiguous revision to + walk to. + """ + initial: Optional[_RevisionOrBase] + if isinstance(start, str): + initial = self.get_revision(start) + else: + initial = start + + children: Sequence[Optional[_RevisionOrBase]] + for _ in range(abs(steps)): + if steps > 0: + assert initial != "base" # type: ignore[comparison-overlap] + # Walk up + walk_up = [ + is_revision(rev) + for rev in self.get_revisions( + self.bases if initial is None else initial.nextrev + ) + ] + if branch_label: + children = self.filter_for_lineage(walk_up, branch_label) + else: + children = walk_up + else: + # Walk down + if initial == "base": # type: ignore[comparison-overlap] + children = () + else: + children = self.get_revisions( + self.heads + if initial is None + else initial.down_revision + ) + if not children: + children = ("base",) + if not children: + # This will return an invalid result if no_overwalk, otherwise + # further steps will stay where we are. + ret = None if no_overwalk else initial + return ret + elif len(children) > 1: + raise RevisionError("Ambiguous walk") + initial = children[0] + + return initial + + def _parse_downgrade_target( + self, + current_revisions: _RevisionIdentifierType, + target: _RevisionIdentifierType, + assert_relative_length: bool, + ) -> Tuple[Optional[str], Optional[_RevisionOrBase]]: + """ + Parse downgrade command syntax :target to retrieve the target revision + and branch label (if any) given the :current_revisions stamp of the + database. + + Returns a tuple (branch_label, target_revision) where branch_label + is a string from the command specifying the branch to consider (or + None if no branch given), and target_revision is a Revision object + which the command refers to. target_revisions is None if the command + refers to 'base'. The target may be specified in absolute form, or + relative to :current_revisions. + """ + if target is None: + return None, None + assert isinstance( + target, str + ), "Expected downgrade target in string form" + match = _relative_destination.match(target) + if match: + branch_label, symbol, relative = match.groups() + rel_int = int(relative) + if rel_int >= 0: + if symbol is None: + # Downgrading to current + n is not valid. + raise RevisionError( + "Relative revision %s didn't " + "produce %d migrations" % (relative, abs(rel_int)) + ) + # Find target revision relative to given symbol. + rev = self._walk( + symbol, + rel_int, + branch_label, + no_overwalk=assert_relative_length, + ) + if rev is None: + raise RevisionError("Walked too far") + return branch_label, rev + else: + relative_revision = symbol is None + if relative_revision: + # Find target revision relative to current state. + if branch_label: + cr_tuple = util.to_tuple(current_revisions) + symbol_list: Sequence[str] + symbol_list = self.filter_for_lineage( + cr_tuple, branch_label + ) + if not symbol_list: + # check the case where there are multiple branches + # but there is currently a single heads, since all + # other branch heads are dependent of the current + # single heads. + all_current = cast( + Set[Revision], self._get_all_current(cr_tuple) + ) + sl_all_current = self.filter_for_lineage( + all_current, branch_label + ) + symbol_list = [ + r.revision if r else r # type: ignore[misc] + for r in sl_all_current + ] + + assert len(symbol_list) == 1 + symbol = symbol_list[0] + else: + current_revisions = util.to_tuple(current_revisions) + if not current_revisions: + raise RevisionError( + "Relative revision %s didn't " + "produce %d migrations" + % (relative, abs(rel_int)) + ) + # Have to check uniques here for duplicate rows test. + if len(set(current_revisions)) > 1: + util.warn( + "downgrade -1 from multiple heads is " + "ambiguous; " + "this usage will be disallowed in a future " + "release." + ) + symbol = current_revisions[0] + # Restrict iteration to just the selected branch when + # ambiguous branches are involved. + branch_label = symbol + # Walk down the tree to find downgrade target. + rev = self._walk( + start=self.get_revision(symbol) + if branch_label is None + else self.get_revision("%s@%s" % (branch_label, symbol)), + steps=rel_int, + no_overwalk=assert_relative_length, + ) + if rev is None: + if relative_revision: + raise RevisionError( + "Relative revision %s didn't " + "produce %d migrations" % (relative, abs(rel_int)) + ) + else: + raise RevisionError("Walked too far") + return branch_label, rev + + # No relative destination given, revision specified is absolute. + branch_label, _, symbol = target.rpartition("@") + if not branch_label: + branch_label = None + return branch_label, self.get_revision(symbol) + + def _parse_upgrade_target( + self, + current_revisions: _RevisionIdentifierType, + target: _RevisionIdentifierType, + assert_relative_length: bool, + ) -> Tuple[Optional[_RevisionOrBase], ...]: + """ + Parse upgrade command syntax :target to retrieve the target revision + and given the :current_revisions stamp of the database. + + Returns a tuple of Revision objects which should be iterated/upgraded + to. The target may be specified in absolute form, or relative to + :current_revisions. + """ + if isinstance(target, str): + match = _relative_destination.match(target) + else: + match = None + + if not match: + # No relative destination, target is absolute. + return self.get_revisions(target) + + current_revisions_tup: Union[str, Tuple[Optional[str], ...], None] + current_revisions_tup = util.to_tuple(current_revisions) + + branch_label, symbol, relative_str = match.groups() + relative = int(relative_str) + if relative > 0: + if symbol is None: + if not current_revisions_tup: + current_revisions_tup = (None,) + # Try to filter to a single target (avoid ambiguous branches). + start_revs = current_revisions_tup + if branch_label: + start_revs = self.filter_for_lineage( + self.get_revisions(current_revisions_tup), # type: ignore[arg-type] # noqa: E501 + branch_label, + ) + if not start_revs: + # The requested branch is not a head, so we need to + # backtrack to find a branchpoint. + active_on_branch = self.filter_for_lineage( + self._get_ancestor_nodes( + self.get_revisions(current_revisions_tup) + ), + branch_label, + ) + # Find the tips of this set of revisions (revisions + # without children within the set). + start_revs = tuple( + {rev.revision for rev in active_on_branch} + - { + down + for rev in active_on_branch + for down in rev._normalized_down_revisions + } + ) + if not start_revs: + # We must need to go right back to base to find + # a starting point for this branch. + start_revs = (None,) + if len(start_revs) > 1: + raise RevisionError( + "Ambiguous upgrade from multiple current revisions" + ) + # Walk up from unique target revision. + rev = self._walk( + start=start_revs[0], + steps=relative, + branch_label=branch_label, + no_overwalk=assert_relative_length, + ) + if rev is None: + raise RevisionError( + "Relative revision %s didn't " + "produce %d migrations" % (relative_str, abs(relative)) + ) + return (rev,) + else: + # Walk is relative to a given revision, not the current state. + return ( + self._walk( + start=self.get_revision(symbol), + steps=relative, + branch_label=branch_label, + no_overwalk=assert_relative_length, + ), + ) + else: + if symbol is None: + # Upgrading to current - n is not valid. + raise RevisionError( + "Relative revision %s didn't " + "produce %d migrations" % (relative, abs(relative)) + ) + return ( + self._walk( + start=self.get_revision(symbol) + if branch_label is None + else self.get_revision("%s@%s" % (branch_label, symbol)), + steps=relative, + no_overwalk=assert_relative_length, + ), + ) + + def _collect_downgrade_revisions( + self, + upper: _RevisionIdentifierType, + lower: _RevisionIdentifierType, + inclusive: bool, + implicit_base: bool, + assert_relative_length: bool, + ) -> Tuple[Set[Revision], Tuple[Optional[_RevisionOrBase], ...]]: + """ + Compute the set of current revisions specified by :upper, and the + downgrade target specified by :target. Return all dependents of target + which are currently active. + + :inclusive=True includes the target revision in the set + """ + + branch_label, target_revision = self._parse_downgrade_target( + current_revisions=upper, + target=lower, + assert_relative_length=assert_relative_length, + ) + if target_revision == "base": + target_revision = None + assert target_revision is None or isinstance(target_revision, Revision) + + roots: List[Revision] + # Find candidates to drop. + if target_revision is None: + # Downgrading back to base: find all tree roots. + roots = [ + rev + for rev in self._revision_map.values() + if rev is not None and rev.down_revision is None + ] + elif inclusive: + # inclusive implies target revision should also be dropped + roots = [target_revision] + else: + # Downgrading to fixed target: find all direct children. + roots = [ + is_revision(rev) + for rev in self.get_revisions(target_revision.nextrev) + ] + + if branch_label and len(roots) > 1: + # Need to filter roots. + ancestors = { + rev.revision + for rev in self._get_ancestor_nodes( + [self._resolve_branch(branch_label)], + include_dependencies=False, + ) + } + # Intersection gives the root revisions we are trying to + # rollback with the downgrade. + roots = [ + is_revision(rev) + for rev in self.get_revisions( + {rev.revision for rev in roots}.intersection(ancestors) + ) + ] + + # Ensure we didn't throw everything away when filtering branches. + if len(roots) == 0: + raise RevisionError( + "Not a valid downgrade target from current heads" + ) + + heads = self.get_revisions(upper) + + # Aim is to drop :branch_revision; to do so we also need to drop its + # descendents and anything dependent on it. + downgrade_revisions = set( + self._get_descendant_nodes( + roots, + include_dependencies=True, + omit_immediate_dependencies=False, + ) + ) + active_revisions = set( + self._get_ancestor_nodes(heads, include_dependencies=True) + ) + + # Emit revisions to drop in reverse topological sorted order. + downgrade_revisions.intersection_update(active_revisions) + + if implicit_base: + # Wind other branches back to base. + downgrade_revisions.update( + active_revisions.difference(self._get_ancestor_nodes(roots)) + ) + + if ( + target_revision is not None + and not downgrade_revisions + and target_revision not in heads + ): + # Empty intersection: target revs are not present. + + raise RangeNotAncestorError("Nothing to drop", upper) + + return downgrade_revisions, heads + + def _collect_upgrade_revisions( + self, + upper: _RevisionIdentifierType, + lower: _RevisionIdentifierType, + inclusive: bool, + implicit_base: bool, + assert_relative_length: bool, + ) -> Tuple[Set[Revision], Tuple[Revision, ...]]: + """ + Compute the set of required revisions specified by :upper, and the + current set of active revisions specified by :lower. Find the + difference between the two to compute the required upgrades. + + :inclusive=True includes the current/lower revisions in the set + + :implicit_base=False only returns revisions which are downstream + of the current/lower revisions. Dependencies from branches with + different bases will not be included. + """ + targets: Collection[Revision] = [ + is_revision(rev) + for rev in self._parse_upgrade_target( + current_revisions=lower, + target=upper, + assert_relative_length=assert_relative_length, + ) + ] + + # assert type(targets) is tuple, "targets should be a tuple" + + # Handled named bases (e.g. branch@... -> heads should only produce + # targets on the given branch) + if isinstance(lower, str) and "@" in lower: + branch, _, _ = lower.partition("@") + branch_rev = self.get_revision(branch) + if branch_rev is not None and branch_rev.revision == branch: + # A revision was used as a label; get its branch instead + assert len(branch_rev.branch_labels) == 1 + branch = next(iter(branch_rev.branch_labels)) + targets = { + need for need in targets if branch in need.branch_labels + } + + required_node_set = set( + self._get_ancestor_nodes( + targets, check=True, include_dependencies=True + ) + ).union(targets) + + current_revisions = self.get_revisions(lower) + if not implicit_base and any( + rev not in required_node_set + for rev in current_revisions + if rev is not None + ): + raise RangeNotAncestorError(lower, upper) + assert ( + type(current_revisions) is tuple + ), "current_revisions should be a tuple" + + # Special case where lower = a relative value (get_revisions can't + # find it) + if current_revisions and current_revisions[0] is None: + _, rev = self._parse_downgrade_target( + current_revisions=upper, + target=lower, + assert_relative_length=assert_relative_length, + ) + assert rev + if rev == "base": + current_revisions = tuple() + lower = None + else: + current_revisions = (rev,) + lower = rev.revision + + current_node_set = set( + self._get_ancestor_nodes( + current_revisions, check=True, include_dependencies=True + ) + ).union(current_revisions) + + needs = required_node_set.difference(current_node_set) + + # Include the lower revision (=current_revisions?) in the iteration + if inclusive: + needs.update(is_revision(rev) for rev in self.get_revisions(lower)) + # By default, base is implicit as we want all dependencies returned. + # Base is also implicit if lower = base + # implicit_base=False -> only return direct downstreams of + # current_revisions + if current_revisions and not implicit_base: + lower_descendents = self._get_descendant_nodes( + [is_revision(rev) for rev in current_revisions], + check=True, + include_dependencies=False, + ) + needs.intersection_update(lower_descendents) + + return needs, tuple(targets) + + def _get_all_current( + self, id_: Tuple[str, ...] + ) -> Set[Optional[_RevisionOrBase]]: + top_revs: Set[Optional[_RevisionOrBase]] + top_revs = set(self.get_revisions(id_)) + top_revs.update( + self._get_ancestor_nodes(list(top_revs), include_dependencies=True) + ) + return self._filter_into_branch_heads(top_revs) + + +class Revision: + """Base class for revisioned objects. + + The :class:`.Revision` class is the base of the more public-facing + :class:`.Script` object, which represents a migration script. + The mechanics of revision management and traversal are encapsulated + within :class:`.Revision`, while :class:`.Script` applies this logic + to Python files in a version directory. + + """ + + nextrev: FrozenSet[str] = frozenset() + """following revisions, based on down_revision only.""" + + _all_nextrev: FrozenSet[str] = frozenset() + + revision: str = None # type: ignore[assignment] + """The string revision number.""" + + down_revision: Optional[_RevIdType] = None + """The ``down_revision`` identifier(s) within the migration script. + + Note that the total set of "down" revisions is + down_revision + dependencies. + + """ + + dependencies: Optional[_RevIdType] = None + """Additional revisions which this revision is dependent on. + + From a migration standpoint, these dependencies are added to the + down_revision to form the full iteration. However, the separation + of down_revision from "dependencies" is to assist in navigating + a history that contains many branches, typically a multi-root scenario. + + """ + + branch_labels: Set[str] = None # type: ignore[assignment] + """Optional string/tuple of symbolic names to apply to this + revision's branch""" + + _resolved_dependencies: Tuple[str, ...] + _normalized_resolved_dependencies: Tuple[str, ...] + + @classmethod + def verify_rev_id(cls, revision: str) -> None: + illegal_chars = set(revision).intersection(_revision_illegal_chars) + if illegal_chars: + raise RevisionError( + "Character(s) '%s' not allowed in revision identifier '%s'" + % (", ".join(sorted(illegal_chars)), revision) + ) + + def __init__( + self, + revision: str, + down_revision: Optional[Union[str, Tuple[str, ...]]], + dependencies: Optional[Union[str, Tuple[str, ...]]] = None, + branch_labels: Optional[Union[str, Tuple[str, ...]]] = None, + ) -> None: + if down_revision and revision in util.to_tuple(down_revision): + raise LoopDetected(revision) + elif dependencies is not None and revision in util.to_tuple( + dependencies + ): + raise DependencyLoopDetected(revision) + + self.verify_rev_id(revision) + self.revision = revision + self.down_revision = tuple_rev_as_scalar(util.to_tuple(down_revision)) + self.dependencies = tuple_rev_as_scalar(util.to_tuple(dependencies)) + self._orig_branch_labels = util.to_tuple(branch_labels, default=()) + self.branch_labels = set(self._orig_branch_labels) + + def __repr__(self) -> str: + args = [repr(self.revision), repr(self.down_revision)] + if self.dependencies: + args.append("dependencies=%r" % (self.dependencies,)) + if self.branch_labels: + args.append("branch_labels=%r" % (self.branch_labels,)) + return "%s(%s)" % (self.__class__.__name__, ", ".join(args)) + + def add_nextrev(self, revision: Revision) -> None: + self._all_nextrev = self._all_nextrev.union([revision.revision]) + if self.revision in revision._versioned_down_revisions: + self.nextrev = self.nextrev.union([revision.revision]) + + @property + def _all_down_revisions(self) -> Tuple[str, ...]: + return util.dedupe_tuple( + util.to_tuple(self.down_revision, default=()) + + self._resolved_dependencies + ) + + @property + def _normalized_down_revisions(self) -> Tuple[str, ...]: + """return immediate down revisions for a rev, omitting dependencies + that are still dependencies of ancestors. + + """ + return util.dedupe_tuple( + util.to_tuple(self.down_revision, default=()) + + self._normalized_resolved_dependencies + ) + + @property + def _versioned_down_revisions(self) -> Tuple[str, ...]: + return util.to_tuple(self.down_revision, default=()) + + @property + def is_head(self) -> bool: + """Return True if this :class:`.Revision` is a 'head' revision. + + This is determined based on whether any other :class:`.Script` + within the :class:`.ScriptDirectory` refers to this + :class:`.Script`. Multiple heads can be present. + + """ + return not bool(self.nextrev) + + @property + def _is_real_head(self) -> bool: + return not bool(self._all_nextrev) + + @property + def is_base(self) -> bool: + """Return True if this :class:`.Revision` is a 'base' revision.""" + + return self.down_revision is None + + @property + def _is_real_base(self) -> bool: + """Return True if this :class:`.Revision` is a "real" base revision, + e.g. that it has no dependencies either.""" + + # we use self.dependencies here because this is called up + # in initialization where _real_dependencies isn't set up + # yet + return self.down_revision is None and self.dependencies is None + + @property + def is_branch_point(self) -> bool: + """Return True if this :class:`.Script` is a branch point. + + A branchpoint is defined as a :class:`.Script` which is referred + to by more than one succeeding :class:`.Script`, that is more + than one :class:`.Script` has a `down_revision` identifier pointing + here. + + """ + return len(self.nextrev) > 1 + + @property + def _is_real_branch_point(self) -> bool: + """Return True if this :class:`.Script` is a 'real' branch point, + taking into account dependencies as well. + + """ + return len(self._all_nextrev) > 1 + + @property + def is_merge_point(self) -> bool: + """Return True if this :class:`.Script` is a merge point.""" + + return len(self._versioned_down_revisions) > 1 + + +@overload +def tuple_rev_as_scalar(rev: None) -> None: + ... + + +@overload +def tuple_rev_as_scalar( + rev: Union[Tuple[_T, ...], List[_T]] +) -> Union[_T, Tuple[_T, ...], List[_T]]: + ... + + +def tuple_rev_as_scalar( + rev: Optional[Sequence[_T]], +) -> Union[_T, Sequence[_T], None]: + if not rev: + return None + elif len(rev) == 1: + return rev[0] + else: + return rev + + +def is_revision(rev: Any) -> Revision: + assert isinstance(rev, Revision) + return rev diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/write_hooks.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/write_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..9977147921055b2f5540993188ca495455a2ca7d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/script/write_hooks.py @@ -0,0 +1,179 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +import shlex +import subprocess +import sys +from typing import Any +from typing import Callable +from typing import Dict +from typing import List +from typing import Mapping +from typing import Optional +from typing import Union + +from .. import util +from ..util import compat + + +REVISION_SCRIPT_TOKEN = "REVISION_SCRIPT_FILENAME" + +_registry: dict = {} + + +def register(name: str) -> Callable: + """A function decorator that will register that function as a write hook. + + See the documentation linked below for an example. + + .. seealso:: + + :ref:`post_write_hooks_custom` + + + """ + + def decorate(fn): + _registry[name] = fn + return fn + + return decorate + + +def _invoke( + name: str, revision: str, options: Mapping[str, Union[str, int]] +) -> Any: + """Invokes the formatter registered for the given name. + + :param name: The name of a formatter in the registry + :param revision: A :class:`.MigrationRevision` instance + :param options: A dict containing kwargs passed to the + specified formatter. + :raises: :class:`alembic.util.CommandError` + """ + try: + hook = _registry[name] + except KeyError as ke: + raise util.CommandError( + f"No formatter with name '{name}' registered" + ) from ke + else: + return hook(revision, options) + + +def _run_hooks(path: str, hook_config: Mapping[str, str]) -> None: + """Invoke hooks for a generated revision.""" + + from .base import _split_on_space_comma + + names = _split_on_space_comma.split(hook_config.get("hooks", "")) + + for name in names: + if not name: + continue + opts = { + key[len(name) + 1 :]: hook_config[key] + for key in hook_config + if key.startswith(name + ".") + } + opts["_hook_name"] = name + try: + type_ = opts["type"] + except KeyError as ke: + raise util.CommandError( + f"Key {name}.type is required for post write hook {name!r}" + ) from ke + else: + with util.status( + f"Running post write hook {name!r}", newline=True + ): + _invoke(type_, path, opts) + + +def _parse_cmdline_options(cmdline_options_str: str, path: str) -> List[str]: + """Parse options from a string into a list. + + Also substitutes the revision script token with the actual filename of + the revision script. + + If the revision script token doesn't occur in the options string, it is + automatically prepended. + """ + if REVISION_SCRIPT_TOKEN not in cmdline_options_str: + cmdline_options_str = REVISION_SCRIPT_TOKEN + " " + cmdline_options_str + cmdline_options_list = shlex.split( + cmdline_options_str, posix=compat.is_posix + ) + cmdline_options_list = [ + option.replace(REVISION_SCRIPT_TOKEN, path) + for option in cmdline_options_list + ] + return cmdline_options_list + + +@register("console_scripts") +def console_scripts( + path: str, options: dict, ignore_output: bool = False +) -> None: + try: + entrypoint_name = options["entrypoint"] + except KeyError as ke: + raise util.CommandError( + f"Key {options['_hook_name']}.entrypoint is required for post " + f"write hook {options['_hook_name']!r}" + ) from ke + for entry in compat.importlib_metadata_get("console_scripts"): + if entry.name == entrypoint_name: + impl: Any = entry + break + else: + raise util.CommandError( + f"Could not find entrypoint console_scripts.{entrypoint_name}" + ) + cwd: Optional[str] = options.get("cwd", None) + cmdline_options_str = options.get("options", "") + cmdline_options_list = _parse_cmdline_options(cmdline_options_str, path) + + kw: Dict[str, Any] = {} + if ignore_output: + kw["stdout"] = kw["stderr"] = subprocess.DEVNULL + + subprocess.run( + [ + sys.executable, + "-c", + f"import {impl.module}; {impl.module}.{impl.attr}()", + ] + + cmdline_options_list, + cwd=cwd, + **kw, + ) + + +@register("exec") +def exec_(path: str, options: dict, ignore_output: bool = False) -> None: + try: + executable = options["executable"] + except KeyError as ke: + raise util.CommandError( + f"Key {options['_hook_name']}.executable is required for post " + f"write hook {options['_hook_name']!r}" + ) from ke + cwd: Optional[str] = options.get("cwd", None) + cmdline_options_str = options.get("options", "") + cmdline_options_list = _parse_cmdline_options(cmdline_options_str, path) + + kw: Dict[str, Any] = {} + if ignore_output: + kw["stdout"] = kw["stderr"] = subprocess.DEVNULL + + subprocess.run( + [ + executable, + *cmdline_options_list, + ], + cwd=cwd, + **kw, + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/README b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/README new file mode 100644 index 0000000000000000000000000000000000000000..e0d0858f266ec27b243e8b92301fc7002e1f2745 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/README @@ -0,0 +1 @@ +Generic single-database configuration with an async dbapi. \ No newline at end of file diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/alembic.ini.mako b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/alembic.ini.mako new file mode 100644 index 0000000000000000000000000000000000000000..0e5f43fdefbf43aab57005b532381e50abcca2fc --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/alembic.ini.mako @@ -0,0 +1,114 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = ${script_location} + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python>=3.9 or backports.zoneinfo library. +# Any required deps can installed by adding `alembic[tz]` to the pip requirements +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the +# "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to ${script_location}/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:${script_location}/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the exec runner, execute a binary +# hooks = ruff +# ruff.type = exec +# ruff.executable = %(here)s/.venv/bin/ruff +# ruff.options = --fix REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/env.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/env.py new file mode 100644 index 0000000000000000000000000000000000000000..9f2d51940080a1a7c954a8916dab86f00d5a4aa5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/env.py @@ -0,0 +1,89 @@ +import asyncio +from logging.config import fileConfig + +from sqlalchemy import pool +from sqlalchemy.engine import Connection +from sqlalchemy.ext.asyncio import async_engine_from_config + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +target_metadata = None + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def do_run_migrations(connection: Connection) -> None: + context.configure(connection=connection, target_metadata=target_metadata) + + with context.begin_transaction(): + context.run_migrations() + + +async def run_async_migrations() -> None: + """In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + connectable = async_engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + async with connectable.connect() as connection: + await connection.run_sync(do_run_migrations) + + await connectable.dispose() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode.""" + + asyncio.run(run_async_migrations()) + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/script.py.mako b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/script.py.mako new file mode 100644 index 0000000000000000000000000000000000000000..fbc4b07dcef98b20c6f96b642097f35e8433258e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/async/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/README b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/README new file mode 100644 index 0000000000000000000000000000000000000000..98e4f9c44effe479ed38c66ba922e7bcc672916f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/alembic.ini.mako b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/alembic.ini.mako new file mode 100644 index 0000000000000000000000000000000000000000..29245dd3f5aef640935e62bb9dc305f0130c465b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/alembic.ini.mako @@ -0,0 +1,116 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = ${script_location} + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python>=3.9 or backports.zoneinfo library. +# Any required deps can installed by adding `alembic[tz]` to the pip requirements +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the +# "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to ${script_location}/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:${script_location}/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the exec runner, execute a binary +# hooks = ruff +# ruff.type = exec +# ruff.executable = %(here)s/.venv/bin/ruff +# ruff.options = --fix REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/env.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/env.py new file mode 100644 index 0000000000000000000000000000000000000000..36112a3c68590d6a8e07fea0ce70a5afb38c951a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/env.py @@ -0,0 +1,78 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +target_metadata = None + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, target_metadata=target_metadata + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/script.py.mako b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/script.py.mako new file mode 100644 index 0000000000000000000000000000000000000000..fbc4b07dcef98b20c6f96b642097f35e8433258e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/generic/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/README b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/README new file mode 100644 index 0000000000000000000000000000000000000000..f046ec91427e2f4edd53dcb5409b21955c8fd0af --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/README @@ -0,0 +1,12 @@ +Rudimentary multi-database configuration. + +Multi-DB isn't vastly different from generic. The primary difference is that it +will run the migrations N times (depending on how many databases you have +configured), providing one engine name and associated context for each run. + +That engine name will then allow the migration to restrict what runs within it to +just the appropriate migrations for that engine. You can see this behavior within +the mako template. + +In the provided configuration, you'll need to have `databases` provided in +alembic's config, and an `sqlalchemy.url` provided for each engine name. diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/alembic.ini.mako b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/alembic.ini.mako new file mode 100644 index 0000000000000000000000000000000000000000..c7fbe48228a4c0af4f121bf8cc984ea7f889af7c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/alembic.ini.mako @@ -0,0 +1,121 @@ +# a multi-database configuration. + +[alembic] +# path to migration scripts +script_location = ${script_location} + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python>=3.9 or backports.zoneinfo library. +# Any required deps can installed by adding `alembic[tz]` to the pip requirements +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the +# "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to ${script_location}/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:${script_location}/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +databases = engine1, engine2 + +[engine1] +sqlalchemy.url = driver://user:pass@localhost/dbname + +[engine2] +sqlalchemy.url = driver://user:pass@localhost/dbname2 + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the exec runner, execute a binary +# hooks = ruff +# ruff.type = exec +# ruff.executable = %(here)s/.venv/bin/ruff +# ruff.options = --fix REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/env.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/env.py new file mode 100644 index 0000000000000000000000000000000000000000..e937b64eeed2fd980c214ab87505d75041b581ad --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/env.py @@ -0,0 +1,140 @@ +import logging +from logging.config import fileConfig +import re + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +USE_TWOPHASE = False + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) +logger = logging.getLogger("alembic.env") + +# gather section names referring to different +# databases. These are named "engine1", "engine2" +# in the sample .ini file. +db_names = config.get_main_option("databases", "") + +# add your model's MetaData objects here +# for 'autogenerate' support. These must be set +# up to hold just those tables targeting a +# particular database. table.tometadata() may be +# helpful here in case a "copy" of +# a MetaData is needed. +# from myapp import mymodel +# target_metadata = { +# 'engine1':mymodel.metadata1, +# 'engine2':mymodel.metadata2 +# } +target_metadata = {} + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + # for the --sql use case, run migrations for each URL into + # individual files. + + engines = {} + for name in re.split(r",\s*", db_names): + engines[name] = rec = {} + rec["url"] = context.config.get_section_option(name, "sqlalchemy.url") + + for name, rec in engines.items(): + logger.info("Migrating database %s" % name) + file_ = "%s.sql" % name + logger.info("Writing output to %s" % file_) + with open(file_, "w") as buffer: + context.configure( + url=rec["url"], + output_buffer=buffer, + target_metadata=target_metadata.get(name), + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + with context.begin_transaction(): + context.run_migrations(engine_name=name) + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # for the direct-to-DB use case, start a transaction on all + # engines, then run all migrations, then commit all transactions. + + engines = {} + for name in re.split(r",\s*", db_names): + engines[name] = rec = {} + rec["engine"] = engine_from_config( + context.config.get_section(name, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + for name, rec in engines.items(): + engine = rec["engine"] + rec["connection"] = conn = engine.connect() + + if USE_TWOPHASE: + rec["transaction"] = conn.begin_twophase() + else: + rec["transaction"] = conn.begin() + + try: + for name, rec in engines.items(): + logger.info("Migrating database %s" % name) + context.configure( + connection=rec["connection"], + upgrade_token="%s_upgrades" % name, + downgrade_token="%s_downgrades" % name, + target_metadata=target_metadata.get(name), + ) + context.run_migrations(engine_name=name) + + if USE_TWOPHASE: + for rec in engines.values(): + rec["transaction"].prepare() + + for rec in engines.values(): + rec["transaction"].commit() + except: + for rec in engines.values(): + rec["transaction"].rollback() + raise + finally: + for rec in engines.values(): + rec["connection"].close() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/script.py.mako b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/script.py.mako new file mode 100644 index 0000000000000000000000000000000000000000..6108b8a0dc2a1bef8f8b25fda188ab61ef9bdaf9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/templates/multidb/script.py.mako @@ -0,0 +1,47 @@ +<%! +import re + +%>"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade(engine_name: str) -> None: + globals()["upgrade_%s" % engine_name]() + + +def downgrade(engine_name: str) -> None: + globals()["downgrade_%s" % engine_name]() + +<% + db_names = config.get_main_option("databases") +%> + +## generate an "upgrade_() / downgrade_()" function +## for each database name in the ini file. + +% for db_name in re.split(r',\s*', db_names): + +def upgrade_${db_name}() -> None: + ${context.get("%s_upgrades" % db_name, "pass")} + + +def downgrade_${db_name}() -> None: + ${context.get("%s_downgrades" % db_name, "pass")} + +% endfor diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0407adfe9ceb5ed7071d8fac48813e664468a71b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/__init__.py @@ -0,0 +1,29 @@ +from sqlalchemy.testing import config +from sqlalchemy.testing import emits_warning +from sqlalchemy.testing import engines +from sqlalchemy.testing import exclusions +from sqlalchemy.testing import mock +from sqlalchemy.testing import provide_metadata +from sqlalchemy.testing import skip_if +from sqlalchemy.testing import uses_deprecated +from sqlalchemy.testing.config import combinations +from sqlalchemy.testing.config import fixture +from sqlalchemy.testing.config import requirements as requires + +from .assertions import assert_raises +from .assertions import assert_raises_message +from .assertions import emits_python_deprecation_warning +from .assertions import eq_ +from .assertions import eq_ignore_whitespace +from .assertions import expect_raises +from .assertions import expect_raises_message +from .assertions import expect_sqlalchemy_deprecated +from .assertions import expect_sqlalchemy_deprecated_20 +from .assertions import expect_warnings +from .assertions import is_ +from .assertions import is_false +from .assertions import is_not_ +from .assertions import is_true +from .assertions import ne_ +from .fixtures import TestBase +from .util import resolve_lambda diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/assertions.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/assertions.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9593b713656d7c9a4097c32b5d84b0b570069f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/assertions.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import contextlib +import re +import sys +from typing import Any +from typing import Dict + +from sqlalchemy import exc as sa_exc +from sqlalchemy.engine import default +from sqlalchemy.testing.assertions import _expect_warnings +from sqlalchemy.testing.assertions import eq_ # noqa +from sqlalchemy.testing.assertions import is_ # noqa +from sqlalchemy.testing.assertions import is_false # noqa +from sqlalchemy.testing.assertions import is_not_ # noqa +from sqlalchemy.testing.assertions import is_true # noqa +from sqlalchemy.testing.assertions import ne_ # noqa +from sqlalchemy.util import decorator + +from ..util import sqla_compat + + +def _assert_proper_exception_context(exception): + """assert that any exception we're catching does not have a __context__ + without a __cause__, and that __suppress_context__ is never set. + + Python 3 will report nested as exceptions as "during the handling of + error X, error Y occurred". That's not what we want to do. we want + these exceptions in a cause chain. + + """ + + if ( + exception.__context__ is not exception.__cause__ + and not exception.__suppress_context__ + ): + assert False, ( + "Exception %r was correctly raised but did not set a cause, " + "within context %r as its cause." + % (exception, exception.__context__) + ) + + +def assert_raises(except_cls, callable_, *args, **kw): + return _assert_raises(except_cls, callable_, args, kw, check_context=True) + + +def assert_raises_context_ok(except_cls, callable_, *args, **kw): + return _assert_raises(except_cls, callable_, args, kw) + + +def assert_raises_message(except_cls, msg, callable_, *args, **kwargs): + return _assert_raises( + except_cls, callable_, args, kwargs, msg=msg, check_context=True + ) + + +def assert_raises_message_context_ok( + except_cls, msg, callable_, *args, **kwargs +): + return _assert_raises(except_cls, callable_, args, kwargs, msg=msg) + + +def _assert_raises( + except_cls, callable_, args, kwargs, msg=None, check_context=False +): + with _expect_raises(except_cls, msg, check_context) as ec: + callable_(*args, **kwargs) + return ec.error + + +class _ErrorContainer: + error: Any = None + + +@contextlib.contextmanager +def _expect_raises(except_cls, msg=None, check_context=False): + ec = _ErrorContainer() + if check_context: + are_we_already_in_a_traceback = sys.exc_info()[0] + try: + yield ec + success = False + except except_cls as err: + ec.error = err + success = True + if msg is not None: + assert re.search(msg, str(err), re.UNICODE), f"{msg} !~ {err}" + if check_context and not are_we_already_in_a_traceback: + _assert_proper_exception_context(err) + print(str(err).encode("utf-8")) + + # assert outside the block so it works for AssertionError too ! + assert success, "Callable did not raise an exception" + + +def expect_raises(except_cls, check_context=True): + return _expect_raises(except_cls, check_context=check_context) + + +def expect_raises_message(except_cls, msg, check_context=True): + return _expect_raises(except_cls, msg=msg, check_context=check_context) + + +def eq_ignore_whitespace(a, b, msg=None): + a = re.sub(r"^\s+?|\n", "", a) + a = re.sub(r" {2,}", " ", a) + b = re.sub(r"^\s+?|\n", "", b) + b = re.sub(r" {2,}", " ", b) + + assert a == b, msg or "%r != %r" % (a, b) + + +_dialect_mods: Dict[Any, Any] = {} + + +def _get_dialect(name): + if name is None or name == "default": + return default.DefaultDialect() + else: + d = sqla_compat._create_url(name).get_dialect()() + + if name == "postgresql": + d.implicit_returning = True + elif name == "mssql": + d.legacy_schema_aliasing = False + return d + + +def expect_warnings(*messages, **kw): + """Context manager which expects one or more warnings. + + With no arguments, squelches all SAWarnings emitted via + sqlalchemy.util.warn and sqlalchemy.util.warn_limited. Otherwise + pass string expressions that will match selected warnings via regex; + all non-matching warnings are sent through. + + The expect version **asserts** that the warnings were in fact seen. + + Note that the test suite sets SAWarning warnings to raise exceptions. + + """ + return _expect_warnings(Warning, messages, **kw) + + +def emits_python_deprecation_warning(*messages): + """Decorator form of expect_warnings(). + + Note that emits_warning does **not** assert that the warnings + were in fact seen. + + """ + + @decorator + def decorate(fn, *args, **kw): + with _expect_warnings(DeprecationWarning, assert_=False, *messages): + return fn(*args, **kw) + + return decorate + + +def expect_sqlalchemy_deprecated(*messages, **kw): + return _expect_warnings(sa_exc.SADeprecationWarning, messages, **kw) + + +def expect_sqlalchemy_deprecated_20(*messages, **kw): + return _expect_warnings(sa_exc.RemovedIn20Warning, messages, **kw) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/env.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/env.py new file mode 100644 index 0000000000000000000000000000000000000000..5df7ef8227dd89ac97aaf5115e9d85339223a14d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/env.py @@ -0,0 +1,518 @@ +import importlib.machinery +import os +import shutil +import textwrap + +from sqlalchemy.testing import config +from sqlalchemy.testing import provision + +from . import util as testing_util +from .. import command +from .. import script +from .. import util +from ..script import Script +from ..script import ScriptDirectory + + +def _get_staging_directory(): + if provision.FOLLOWER_IDENT: + return "scratch_%s" % provision.FOLLOWER_IDENT + else: + return "scratch" + + +def staging_env(create=True, template="generic", sourceless=False): + cfg = _testing_config() + if create: + path = os.path.join(_get_staging_directory(), "scripts") + assert not os.path.exists(path), ( + "staging directory %s already exists; poor cleanup?" % path + ) + + command.init(cfg, path, template=template) + if sourceless: + try: + # do an import so that a .pyc/.pyo is generated. + util.load_python_file(path, "env.py") + except AttributeError: + # we don't have the migration context set up yet + # so running the .env py throws this exception. + # theoretically we could be using py_compiler here to + # generate .pyc/.pyo without importing but not really + # worth it. + pass + assert sourceless in ( + "pep3147_envonly", + "simple", + "pep3147_everything", + ), sourceless + make_sourceless( + os.path.join(path, "env.py"), + "pep3147" if "pep3147" in sourceless else "simple", + ) + + sc = script.ScriptDirectory.from_config(cfg) + return sc + + +def clear_staging_env(): + from sqlalchemy.testing import engines + + engines.testing_reaper.close_all() + shutil.rmtree(_get_staging_directory(), True) + + +def script_file_fixture(txt): + dir_ = os.path.join(_get_staging_directory(), "scripts") + path = os.path.join(dir_, "script.py.mako") + with open(path, "w") as f: + f.write(txt) + + +def env_file_fixture(txt): + dir_ = os.path.join(_get_staging_directory(), "scripts") + txt = ( + """ +from alembic import context + +config = context.config +""" + + txt + ) + + path = os.path.join(dir_, "env.py") + pyc_path = util.pyc_file_from_path(path) + if pyc_path: + os.unlink(pyc_path) + + with open(path, "w") as f: + f.write(txt) + + +def _sqlite_file_db(tempname="foo.db", future=False, scope=None, **options): + dir_ = os.path.join(_get_staging_directory(), "scripts") + url = "sqlite:///%s/%s" % (dir_, tempname) + if scope and util.sqla_14: + options["scope"] = scope + return testing_util.testing_engine(url=url, future=future, options=options) + + +def _sqlite_testing_config(sourceless=False, future=False): + dir_ = os.path.join(_get_staging_directory(), "scripts") + url = "sqlite:///%s/foo.db" % dir_ + + sqlalchemy_future = future or ("future" in config.db.__class__.__module__) + + return _write_config_file( + """ +[alembic] +script_location = %s +sqlalchemy.url = %s +sourceless = %s +%s + +[loggers] +keys = root,sqlalchemy + +[handlers] +keys = console + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = DEBUG +handlers = +qualname = sqlalchemy.engine + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatters] +keys = generic + +[formatter_generic] +format = %%(levelname)-5.5s [%%(name)s] %%(message)s +datefmt = %%H:%%M:%%S + """ + % ( + dir_, + url, + "true" if sourceless else "false", + "sqlalchemy.future = true" if sqlalchemy_future else "", + ) + ) + + +def _multi_dir_testing_config(sourceless=False, extra_version_location=""): + dir_ = os.path.join(_get_staging_directory(), "scripts") + sqlalchemy_future = "future" in config.db.__class__.__module__ + + url = "sqlite:///%s/foo.db" % dir_ + + return _write_config_file( + """ +[alembic] +script_location = %s +sqlalchemy.url = %s +sqlalchemy.future = %s +sourceless = %s +version_locations = %%(here)s/model1/ %%(here)s/model2/ %%(here)s/model3/ %s + +[loggers] +keys = root + +[handlers] +keys = console + +[logger_root] +level = WARN +handlers = console +qualname = + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatters] +keys = generic + +[formatter_generic] +format = %%(levelname)-5.5s [%%(name)s] %%(message)s +datefmt = %%H:%%M:%%S + """ + % ( + dir_, + url, + "true" if sqlalchemy_future else "false", + "true" if sourceless else "false", + extra_version_location, + ) + ) + + +def _no_sql_testing_config(dialect="postgresql", directives=""): + """use a postgresql url with no host so that + connections guaranteed to fail""" + dir_ = os.path.join(_get_staging_directory(), "scripts") + return _write_config_file( + """ +[alembic] +script_location = %s +sqlalchemy.url = %s:// +%s + +[loggers] +keys = root + +[handlers] +keys = console + +[logger_root] +level = WARN +handlers = console +qualname = + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatters] +keys = generic + +[formatter_generic] +format = %%(levelname)-5.5s [%%(name)s] %%(message)s +datefmt = %%H:%%M:%%S + +""" + % (dir_, dialect, directives) + ) + + +def _write_config_file(text): + cfg = _testing_config() + with open(cfg.config_file_name, "w") as f: + f.write(text) + return cfg + + +def _testing_config(): + from alembic.config import Config + + if not os.access(_get_staging_directory(), os.F_OK): + os.mkdir(_get_staging_directory()) + return Config(os.path.join(_get_staging_directory(), "test_alembic.ini")) + + +def write_script( + scriptdir, rev_id, content, encoding="ascii", sourceless=False +): + old = scriptdir.revision_map.get_revision(rev_id) + path = old.path + + content = textwrap.dedent(content) + if encoding: + content = content.encode(encoding) + with open(path, "wb") as fp: + fp.write(content) + pyc_path = util.pyc_file_from_path(path) + if pyc_path: + os.unlink(pyc_path) + script = Script._from_path(scriptdir, path) + old = scriptdir.revision_map.get_revision(script.revision) + if old.down_revision != script.down_revision: + raise Exception( + "Can't change down_revision " "on a refresh operation." + ) + scriptdir.revision_map.add_revision(script, _replace=True) + + if sourceless: + make_sourceless( + path, "pep3147" if sourceless == "pep3147_everything" else "simple" + ) + + +def make_sourceless(path, style): + import py_compile + + py_compile.compile(path) + + if style == "simple": + pyc_path = util.pyc_file_from_path(path) + suffix = importlib.machinery.BYTECODE_SUFFIXES[0] + filepath, ext = os.path.splitext(path) + simple_pyc_path = filepath + suffix + shutil.move(pyc_path, simple_pyc_path) + pyc_path = simple_pyc_path + else: + assert style in ("pep3147", "simple") + pyc_path = util.pyc_file_from_path(path) + + assert os.access(pyc_path, os.F_OK) + + os.unlink(path) + + +def three_rev_fixture(cfg): + a = util.rev_id() + b = util.rev_id() + c = util.rev_id() + + script = ScriptDirectory.from_config(cfg) + script.generate_revision(a, "revision a", refresh=True, head="base") + write_script( + script, + a, + """\ +"Rev A" +revision = '%s' +down_revision = None + +from alembic import op + + +def upgrade(): + op.execute("CREATE STEP 1") + + +def downgrade(): + op.execute("DROP STEP 1") + +""" + % a, + ) + + script.generate_revision(b, "revision b", refresh=True, head=a) + write_script( + script, + b, + f"""# coding: utf-8 +"Rev B, méil, %3" +revision = '{b}' +down_revision = '{a}' + +from alembic import op + + +def upgrade(): + op.execute("CREATE STEP 2") + + +def downgrade(): + op.execute("DROP STEP 2") + +""", + encoding="utf-8", + ) + + script.generate_revision(c, "revision c", refresh=True, head=b) + write_script( + script, + c, + """\ +"Rev C" +revision = '%s' +down_revision = '%s' + +from alembic import op + + +def upgrade(): + op.execute("CREATE STEP 3") + + +def downgrade(): + op.execute("DROP STEP 3") + +""" + % (c, b), + ) + return a, b, c + + +def multi_heads_fixture(cfg, a, b, c): + """Create a multiple head fixture from the three-revs fixture""" + + # a->b->c + # -> d -> e + # -> f + d = util.rev_id() + e = util.rev_id() + f = util.rev_id() + + script = ScriptDirectory.from_config(cfg) + script.generate_revision( + d, "revision d from b", head=b, splice=True, refresh=True + ) + write_script( + script, + d, + """\ +"Rev D" +revision = '%s' +down_revision = '%s' + +from alembic import op + + +def upgrade(): + op.execute("CREATE STEP 4") + + +def downgrade(): + op.execute("DROP STEP 4") + +""" + % (d, b), + ) + + script.generate_revision( + e, "revision e from d", head=d, splice=True, refresh=True + ) + write_script( + script, + e, + """\ +"Rev E" +revision = '%s' +down_revision = '%s' + +from alembic import op + + +def upgrade(): + op.execute("CREATE STEP 5") + + +def downgrade(): + op.execute("DROP STEP 5") + +""" + % (e, d), + ) + + script.generate_revision( + f, "revision f from b", head=b, splice=True, refresh=True + ) + write_script( + script, + f, + """\ +"Rev F" +revision = '%s' +down_revision = '%s' + +from alembic import op + + +def upgrade(): + op.execute("CREATE STEP 6") + + +def downgrade(): + op.execute("DROP STEP 6") + +""" + % (f, b), + ) + + return d, e, f + + +def _multidb_testing_config(engines): + """alembic.ini fixture to work exactly with the 'multidb' template""" + + dir_ = os.path.join(_get_staging_directory(), "scripts") + + sqlalchemy_future = "future" in config.db.__class__.__module__ + + databases = ", ".join(engines.keys()) + engines = "\n\n".join( + "[%s]\n" "sqlalchemy.url = %s" % (key, value.url) + for key, value in engines.items() + ) + + return _write_config_file( + """ +[alembic] +script_location = %s +sourceless = false +sqlalchemy.future = %s +databases = %s + +%s +[loggers] +keys = root + +[handlers] +keys = console + +[logger_root] +level = WARN +handlers = console +qualname = + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatters] +keys = generic + +[formatter_generic] +format = %%(levelname)-5.5s [%%(name)s] %%(message)s +datefmt = %%H:%%M:%%S + """ + % (dir_, "true" if sqlalchemy_future else "false", databases, engines) + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/fixtures.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..4b83a745f3f5dbafbd0a0c073635122f888e797b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/fixtures.py @@ -0,0 +1,306 @@ +from __future__ import annotations + +import configparser +from contextlib import contextmanager +import io +import re +from typing import Any +from typing import Dict + +from sqlalchemy import Column +from sqlalchemy import inspect +from sqlalchemy import MetaData +from sqlalchemy import String +from sqlalchemy import Table +from sqlalchemy import testing +from sqlalchemy import text +from sqlalchemy.testing import config +from sqlalchemy.testing import mock +from sqlalchemy.testing.assertions import eq_ +from sqlalchemy.testing.fixtures import TablesTest as SQLAlchemyTablesTest +from sqlalchemy.testing.fixtures import TestBase as SQLAlchemyTestBase + +import alembic +from .assertions import _get_dialect +from ..environment import EnvironmentContext +from ..migration import MigrationContext +from ..operations import Operations +from ..util import sqla_compat +from ..util.sqla_compat import create_mock_engine +from ..util.sqla_compat import sqla_14 +from ..util.sqla_compat import sqla_2 + + +testing_config = configparser.ConfigParser() +testing_config.read(["test.cfg"]) + + +class TestBase(SQLAlchemyTestBase): + is_sqlalchemy_future = sqla_2 + + @testing.fixture() + def ops_context(self, migration_context): + with migration_context.begin_transaction(_per_migration=True): + yield Operations(migration_context) + + @testing.fixture + def migration_context(self, connection): + return MigrationContext.configure( + connection, opts=dict(transaction_per_migration=True) + ) + + @testing.fixture + def connection(self): + with config.db.connect() as conn: + yield conn + + +class TablesTest(TestBase, SQLAlchemyTablesTest): + pass + + +if sqla_14: + from sqlalchemy.testing.fixtures import FutureEngineMixin +else: + + class FutureEngineMixin: # type:ignore[no-redef] + __requires__ = ("sqlalchemy_14",) + + +FutureEngineMixin.is_sqlalchemy_future = True + + +def capture_db(dialect="postgresql://"): + buf = [] + + def dump(sql, *multiparams, **params): + buf.append(str(sql.compile(dialect=engine.dialect))) + + engine = create_mock_engine(dialect, dump) + return engine, buf + + +_engs: Dict[Any, Any] = {} + + +@contextmanager +def capture_context_buffer(**kw): + if kw.pop("bytes_io", False): + buf = io.BytesIO() + else: + buf = io.StringIO() + + kw.update({"dialect_name": "sqlite", "output_buffer": buf}) + conf = EnvironmentContext.configure + + def configure(*arg, **opt): + opt.update(**kw) + return conf(*arg, **opt) + + with mock.patch.object(EnvironmentContext, "configure", configure): + yield buf + + +@contextmanager +def capture_engine_context_buffer(**kw): + from .env import _sqlite_file_db + from sqlalchemy import event + + buf = io.StringIO() + + eng = _sqlite_file_db() + + conn = eng.connect() + + @event.listens_for(conn, "before_cursor_execute") + def bce(conn, cursor, statement, parameters, context, executemany): + buf.write(statement + "\n") + + kw.update({"connection": conn}) + conf = EnvironmentContext.configure + + def configure(*arg, **opt): + opt.update(**kw) + return conf(*arg, **opt) + + with mock.patch.object(EnvironmentContext, "configure", configure): + yield buf + + +def op_fixture( + dialect="default", + as_sql=False, + naming_convention=None, + literal_binds=False, + native_boolean=None, +): + opts = {} + if naming_convention: + opts["target_metadata"] = MetaData(naming_convention=naming_convention) + + class buffer_: + def __init__(self): + self.lines = [] + + def write(self, msg): + msg = msg.strip() + msg = re.sub(r"[\n\t]", "", msg) + if as_sql: + # the impl produces soft tabs, + # so search for blocks of 4 spaces + msg = re.sub(r" ", "", msg) + msg = re.sub(r"\;\n*$", "", msg) + + self.lines.append(msg) + + def flush(self): + pass + + buf = buffer_() + + class ctx(MigrationContext): + def get_buf(self): + return buf + + def clear_assertions(self): + buf.lines[:] = [] + + def assert_(self, *sql): + # TODO: make this more flexible about + # whitespace and such + eq_(buf.lines, [re.sub(r"[\n\t]", "", s) for s in sql]) + + def assert_contains(self, sql): + for stmt in buf.lines: + if re.sub(r"[\n\t]", "", sql) in stmt: + return + else: + assert False, "Could not locate fragment %r in %r" % ( + sql, + buf.lines, + ) + + if as_sql: + opts["as_sql"] = as_sql + if literal_binds: + opts["literal_binds"] = literal_binds + if not sqla_14 and dialect == "mariadb": + ctx_dialect = _get_dialect("mysql") + ctx_dialect.server_version_info = (10, 4, 0, "MariaDB") + + else: + ctx_dialect = _get_dialect(dialect) + if native_boolean is not None: + ctx_dialect.supports_native_boolean = native_boolean + # this is new as of SQLAlchemy 1.2.7 and is used by SQL Server, + # which breaks assumptions in the alembic test suite + ctx_dialect.non_native_boolean_check_constraint = True + if not as_sql: + + def execute(stmt, *multiparam, **param): + if isinstance(stmt, str): + stmt = text(stmt) + assert stmt.supports_execution + sql = str(stmt.compile(dialect=ctx_dialect)) + + buf.write(sql) + + connection = mock.Mock(dialect=ctx_dialect, execute=execute) + else: + opts["output_buffer"] = buf + connection = None + context = ctx(ctx_dialect, connection, opts) + + alembic.op._proxy = Operations(context) + return context + + +class AlterColRoundTripFixture: + # since these tests are about syntax, use more recent SQLAlchemy as some of + # the type / server default compare logic might not work on older + # SQLAlchemy versions as seems to be the case for SQLAlchemy 1.1 on Oracle + + __requires__ = ("alter_column",) + + def setUp(self): + self.conn = config.db.connect() + self.ctx = MigrationContext.configure(self.conn) + self.op = Operations(self.ctx) + self.metadata = MetaData() + + def _compare_type(self, t1, t2): + c1 = Column("q", t1) + c2 = Column("q", t2) + assert not self.ctx.impl.compare_type( + c1, c2 + ), "Type objects %r and %r didn't compare as equivalent" % (t1, t2) + + def _compare_server_default(self, t1, s1, t2, s2): + c1 = Column("q", t1, server_default=s1) + c2 = Column("q", t2, server_default=s2) + assert not self.ctx.impl.compare_server_default( + c1, c2, s2, s1 + ), "server defaults %r and %r didn't compare as equivalent" % (s1, s2) + + def tearDown(self): + sqla_compat._safe_rollback_connection_transaction(self.conn) + with self.conn.begin(): + self.metadata.drop_all(self.conn) + self.conn.close() + + def _run_alter_col(self, from_, to_, compare=None): + column = Column( + from_.get("name", "colname"), + from_.get("type", String(10)), + nullable=from_.get("nullable", True), + server_default=from_.get("server_default", None), + # comment=from_.get("comment", None) + ) + t = Table("x", self.metadata, column) + + with sqla_compat._ensure_scope_for_ddl(self.conn): + t.create(self.conn) + insp = inspect(self.conn) + old_col = insp.get_columns("x")[0] + + # TODO: conditional comment support + self.op.alter_column( + "x", + column.name, + existing_type=column.type, + existing_server_default=column.server_default + if column.server_default is not None + else False, + existing_nullable=True if column.nullable else False, + # existing_comment=column.comment, + nullable=to_.get("nullable", None), + # modify_comment=False, + server_default=to_.get("server_default", False), + new_column_name=to_.get("name", None), + type_=to_.get("type", None), + ) + + insp = inspect(self.conn) + new_col = insp.get_columns("x")[0] + + if compare is None: + compare = to_ + + eq_( + new_col["name"], + compare["name"] if "name" in compare else column.name, + ) + self._compare_type( + new_col["type"], compare.get("type", old_col["type"]) + ) + eq_(new_col["nullable"], compare.get("nullable", column.nullable)) + self._compare_server_default( + new_col["type"], + new_col.get("default", None), + compare.get("type", old_col["type"]), + compare["server_default"].text + if "server_default" in compare + else column.server_default.arg.text + if column.server_default is not None + else None, + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/plugin/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/plugin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/plugin/bootstrap.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/plugin/bootstrap.py new file mode 100644 index 0000000000000000000000000000000000000000..d4a2c5521847f6d34003b49b2826ae49b1d84c29 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/plugin/bootstrap.py @@ -0,0 +1,4 @@ +""" +Bootstrapper for test framework plugins. + +""" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/requirements.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..6e07e28ea48a7615ad3a1d8a874873eba97ee148 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/requirements.py @@ -0,0 +1,210 @@ +from sqlalchemy.testing.requirements import Requirements + +from alembic import util +from alembic.util import sqla_compat +from ..testing import exclusions + + +class SuiteRequirements(Requirements): + @property + def schemas(self): + """Target database must support external schemas, and have one + named 'test_schema'.""" + + return exclusions.open() + + @property + def autocommit_isolation(self): + """target database should support 'AUTOCOMMIT' isolation level""" + + return exclusions.closed() + + @property + def materialized_views(self): + """needed for sqlalchemy compat""" + return exclusions.closed() + + @property + def unique_constraint_reflection(self): + def doesnt_have_check_uq_constraints(config): + from sqlalchemy import inspect + + insp = inspect(config.db) + try: + insp.get_unique_constraints("x") + except NotImplementedError: + return True + except TypeError: + return True + except Exception: + pass + return False + + return exclusions.skip_if(doesnt_have_check_uq_constraints) + + @property + def sequences(self): + """Target database must support SEQUENCEs.""" + + return exclusions.only_if( + [lambda config: config.db.dialect.supports_sequences], + "no sequence support", + ) + + @property + def foreign_key_match(self): + return exclusions.open() + + @property + def foreign_key_constraint_reflection(self): + return exclusions.open() + + @property + def check_constraints_w_enforcement(self): + """Target database must support check constraints + and also enforce them.""" + + return exclusions.open() + + @property + def reflects_pk_names(self): + return exclusions.closed() + + @property + def reflects_fk_options(self): + return exclusions.closed() + + @property + def sqlalchemy_14(self): + return exclusions.skip_if( + lambda config: not util.sqla_14, + "SQLAlchemy 1.4 or greater required", + ) + + @property + def sqlalchemy_1x(self): + return exclusions.skip_if( + lambda config: util.sqla_2, + "SQLAlchemy 1.x test", + ) + + @property + def sqlalchemy_2(self): + return exclusions.skip_if( + lambda config: not util.sqla_2, + "SQLAlchemy 2.x test", + ) + + @property + def asyncio(self): + def go(config): + try: + import greenlet # noqa: F401 + except ImportError: + return False + else: + return True + + return self.sqlalchemy_14 + exclusions.only_if(go) + + @property + def comments(self): + return exclusions.only_if( + lambda config: config.db.dialect.supports_comments + ) + + @property + def alter_column(self): + return exclusions.open() + + @property + def computed_columns(self): + return exclusions.closed() + + @property + def computed_columns_api(self): + return exclusions.only_if( + exclusions.BooleanPredicate(sqla_compat.has_computed) + ) + + @property + def computed_reflects_normally(self): + return exclusions.only_if( + exclusions.BooleanPredicate(sqla_compat.has_computed_reflection) + ) + + @property + def computed_reflects_as_server_default(self): + return exclusions.closed() + + @property + def computed_doesnt_reflect_as_server_default(self): + return exclusions.closed() + + @property + def autoincrement_on_composite_pk(self): + return exclusions.closed() + + @property + def fk_ondelete_is_reflected(self): + return exclusions.closed() + + @property + def fk_onupdate_is_reflected(self): + return exclusions.closed() + + @property + def fk_onupdate(self): + return exclusions.open() + + @property + def fk_ondelete_restrict(self): + return exclusions.open() + + @property + def fk_onupdate_restrict(self): + return exclusions.open() + + @property + def fk_ondelete_noaction(self): + return exclusions.open() + + @property + def fk_initially(self): + return exclusions.closed() + + @property + def fk_deferrable(self): + return exclusions.closed() + + @property + def fk_deferrable_is_reflected(self): + return exclusions.closed() + + @property + def fk_names(self): + return exclusions.open() + + @property + def integer_subtype_comparisons(self): + return exclusions.open() + + @property + def no_name_normalize(self): + return exclusions.skip_if( + lambda config: config.db.dialect.requires_name_normalize + ) + + @property + def identity_columns(self): + return exclusions.closed() + + @property + def identity_columns_alter(self): + return exclusions.closed() + + @property + def identity_columns_api(self): + return exclusions.only_if( + exclusions.BooleanPredicate(sqla_compat.has_identity) + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/schemacompare.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/schemacompare.py new file mode 100644 index 0000000000000000000000000000000000000000..204cc4ddc15b1457cdbacb2c238a625e19c49100 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/schemacompare.py @@ -0,0 +1,169 @@ +from itertools import zip_longest + +from sqlalchemy import schema +from sqlalchemy.sql.elements import ClauseList + + +class CompareTable: + def __init__(self, table): + self.table = table + + def __eq__(self, other): + if self.table.name != other.name or self.table.schema != other.schema: + return False + + for c1, c2 in zip_longest(self.table.c, other.c): + if (c1 is None and c2 is not None) or ( + c2 is None and c1 is not None + ): + return False + if CompareColumn(c1) != c2: + return False + + return True + + # TODO: compare constraints, indexes + + def __ne__(self, other): + return not self.__eq__(other) + + +class CompareColumn: + def __init__(self, column): + self.column = column + + def __eq__(self, other): + return ( + self.column.name == other.name + and self.column.nullable == other.nullable + ) + # TODO: datatypes etc + + def __ne__(self, other): + return not self.__eq__(other) + + +class CompareIndex: + def __init__(self, index, name_only=False): + self.index = index + self.name_only = name_only + + def __eq__(self, other): + if self.name_only: + return self.index.name == other.name + else: + return ( + str(schema.CreateIndex(self.index)) + == str(schema.CreateIndex(other)) + and self.index.dialect_kwargs == other.dialect_kwargs + ) + + def __ne__(self, other): + return not self.__eq__(other) + + def __repr__(self): + expr = ClauseList(*self.index.expressions) + try: + expr_str = expr.compile().string + except Exception: + expr_str = str(expr) + return f"" + + +class CompareCheckConstraint: + def __init__(self, constraint): + self.constraint = constraint + + def __eq__(self, other): + return ( + isinstance(other, schema.CheckConstraint) + and self.constraint.name == other.name + and (str(self.constraint.sqltext) == str(other.sqltext)) + and (other.table.name == self.constraint.table.name) + and other.table.schema == self.constraint.table.schema + ) + + def __ne__(self, other): + return not self.__eq__(other) + + +class CompareForeignKey: + def __init__(self, constraint): + self.constraint = constraint + + def __eq__(self, other): + r1 = ( + isinstance(other, schema.ForeignKeyConstraint) + and self.constraint.name == other.name + and (other.table.name == self.constraint.table.name) + and other.table.schema == self.constraint.table.schema + ) + if not r1: + return False + for c1, c2 in zip_longest(self.constraint.columns, other.columns): + if (c1 is None and c2 is not None) or ( + c2 is None and c1 is not None + ): + return False + if CompareColumn(c1) != c2: + return False + return True + + def __ne__(self, other): + return not self.__eq__(other) + + +class ComparePrimaryKey: + def __init__(self, constraint): + self.constraint = constraint + + def __eq__(self, other): + r1 = ( + isinstance(other, schema.PrimaryKeyConstraint) + and self.constraint.name == other.name + and (other.table.name == self.constraint.table.name) + and other.table.schema == self.constraint.table.schema + ) + if not r1: + return False + + for c1, c2 in zip_longest(self.constraint.columns, other.columns): + if (c1 is None and c2 is not None) or ( + c2 is None and c1 is not None + ): + return False + if CompareColumn(c1) != c2: + return False + + return True + + def __ne__(self, other): + return not self.__eq__(other) + + +class CompareUniqueConstraint: + def __init__(self, constraint): + self.constraint = constraint + + def __eq__(self, other): + r1 = ( + isinstance(other, schema.UniqueConstraint) + and self.constraint.name == other.name + and (other.table.name == self.constraint.table.name) + and other.table.schema == self.constraint.table.schema + ) + if not r1: + return False + + for c1, c2 in zip_longest(self.constraint.columns, other.columns): + if (c1 is None and c2 is not None) or ( + c2 is None and c1 is not None + ): + return False + if CompareColumn(c1) != c2: + return False + + return True + + def __ne__(self, other): + return not self.__eq__(other) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3da498d289ed11e1eb140384db8d601bfcd524aa --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/__init__.py @@ -0,0 +1,7 @@ +from .test_autogen_comments import * # noqa +from .test_autogen_computed import * # noqa +from .test_autogen_diffs import * # noqa +from .test_autogen_fks import * # noqa +from .test_autogen_identity import * # noqa +from .test_environment import * # noqa +from .test_op import * # noqa diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/_autogen_fixtures.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/_autogen_fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..d838ebef1068b5cc38a4a18f1b16b6cd00876581 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/_autogen_fixtures.py @@ -0,0 +1,335 @@ +from __future__ import annotations + +from typing import Any +from typing import Dict +from typing import Set + +from sqlalchemy import CHAR +from sqlalchemy import CheckConstraint +from sqlalchemy import Column +from sqlalchemy import event +from sqlalchemy import ForeignKey +from sqlalchemy import Index +from sqlalchemy import inspect +from sqlalchemy import Integer +from sqlalchemy import MetaData +from sqlalchemy import Numeric +from sqlalchemy import String +from sqlalchemy import Table +from sqlalchemy import Text +from sqlalchemy import text +from sqlalchemy import UniqueConstraint + +from ... import autogenerate +from ... import util +from ...autogenerate import api +from ...ddl.base import _fk_spec +from ...migration import MigrationContext +from ...operations import ops +from ...testing import config +from ...testing import eq_ +from ...testing.env import clear_staging_env +from ...testing.env import staging_env + +names_in_this_test: Set[Any] = set() + + +@event.listens_for(Table, "after_parent_attach") +def new_table(table, parent): + names_in_this_test.add(table.name) + + +def _default_include_object(obj, name, type_, reflected, compare_to): + if type_ == "table": + return name in names_in_this_test + else: + return True + + +_default_object_filters: Any = _default_include_object + +_default_name_filters: Any = None + + +class ModelOne: + __requires__ = ("unique_constraint_reflection",) + + schema: Any = None + + @classmethod + def _get_db_schema(cls): + schema = cls.schema + + m = MetaData(schema=schema) + + Table( + "user", + m, + Column("id", Integer, primary_key=True), + Column("name", String(50)), + Column("a1", Text), + Column("pw", String(50)), + Index("pw_idx", "pw"), + ) + + Table( + "address", + m, + Column("id", Integer, primary_key=True), + Column("email_address", String(100), nullable=False), + ) + + Table( + "order", + m, + Column("order_id", Integer, primary_key=True), + Column( + "amount", + Numeric(8, 2), + nullable=False, + server_default=text("0"), + ), + CheckConstraint("amount >= 0", name="ck_order_amount"), + ) + + Table( + "extra", + m, + Column("x", CHAR), + Column("uid", Integer, ForeignKey("user.id")), + ) + + return m + + @classmethod + def _get_model_schema(cls): + schema = cls.schema + + m = MetaData(schema=schema) + + Table( + "user", + m, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", Text, server_default="x"), + ) + + Table( + "address", + m, + Column("id", Integer, primary_key=True), + Column("email_address", String(100), nullable=False), + Column("street", String(50)), + UniqueConstraint("email_address", name="uq_email"), + ) + + Table( + "order", + m, + Column("order_id", Integer, primary_key=True), + Column( + "amount", + Numeric(10, 2), + nullable=True, + server_default=text("0"), + ), + Column("user_id", Integer, ForeignKey("user.id")), + CheckConstraint("amount > -1", name="ck_order_amount"), + ) + + Table( + "item", + m, + Column("id", Integer, primary_key=True), + Column("description", String(100)), + Column("order_id", Integer, ForeignKey("order.order_id")), + CheckConstraint("len(description) > 5"), + ) + return m + + +class _ComparesFKs: + def _assert_fk_diff( + self, + diff, + type_, + source_table, + source_columns, + target_table, + target_columns, + name=None, + conditional_name=None, + source_schema=None, + onupdate=None, + ondelete=None, + initially=None, + deferrable=None, + ): + # the public API for ForeignKeyConstraint was not very rich + # in 0.7, 0.8, so here we use the well-known but slightly + # private API to get at its elements + ( + fk_source_schema, + fk_source_table, + fk_source_columns, + fk_target_schema, + fk_target_table, + fk_target_columns, + fk_onupdate, + fk_ondelete, + fk_deferrable, + fk_initially, + ) = _fk_spec(diff[1]) + + eq_(diff[0], type_) + eq_(fk_source_table, source_table) + eq_(fk_source_columns, source_columns) + eq_(fk_target_table, target_table) + eq_(fk_source_schema, source_schema) + eq_(fk_onupdate, onupdate) + eq_(fk_ondelete, ondelete) + eq_(fk_initially, initially) + eq_(fk_deferrable, deferrable) + + eq_([elem.column.name for elem in diff[1].elements], target_columns) + if conditional_name is not None: + if conditional_name == "servergenerated": + fks = inspect(self.bind).get_foreign_keys(source_table) + server_fk_name = fks[0]["name"] + eq_(diff[1].name, server_fk_name) + else: + eq_(diff[1].name, conditional_name) + else: + eq_(diff[1].name, name) + + +class AutogenTest(_ComparesFKs): + def _flatten_diffs(self, diffs): + for d in diffs: + if isinstance(d, list): + yield from self._flatten_diffs(d) + else: + yield d + + @classmethod + def _get_bind(cls): + return config.db + + configure_opts: Dict[Any, Any] = {} + + @classmethod + def setup_class(cls): + staging_env() + cls.bind = cls._get_bind() + cls.m1 = cls._get_db_schema() + cls.m1.create_all(cls.bind) + cls.m2 = cls._get_model_schema() + + @classmethod + def teardown_class(cls): + cls.m1.drop_all(cls.bind) + clear_staging_env() + + def setUp(self): + self.conn = conn = self.bind.connect() + ctx_opts = { + "compare_type": True, + "compare_server_default": True, + "target_metadata": self.m2, + "upgrade_token": "upgrades", + "downgrade_token": "downgrades", + "alembic_module_prefix": "op.", + "sqlalchemy_module_prefix": "sa.", + "include_object": _default_object_filters, + "include_name": _default_name_filters, + } + if self.configure_opts: + ctx_opts.update(self.configure_opts) + self.context = context = MigrationContext.configure( + connection=conn, opts=ctx_opts + ) + + self.autogen_context = api.AutogenContext(context, self.m2) + + def tearDown(self): + self.conn.close() + + def _update_context( + self, object_filters=None, name_filters=None, include_schemas=None + ): + if include_schemas is not None: + self.autogen_context.opts["include_schemas"] = include_schemas + if object_filters is not None: + self.autogen_context._object_filters = [object_filters] + if name_filters is not None: + self.autogen_context._name_filters = [name_filters] + return self.autogen_context + + +class AutogenFixtureTest(_ComparesFKs): + def _fixture( + self, + m1, + m2, + include_schemas=False, + opts=None, + object_filters=_default_object_filters, + name_filters=_default_name_filters, + return_ops=False, + max_identifier_length=None, + ): + if max_identifier_length: + dialect = self.bind.dialect + existing_length = dialect.max_identifier_length + dialect.max_identifier_length = ( + dialect._user_defined_max_identifier_length + ) = max_identifier_length + try: + self._alembic_metadata, model_metadata = m1, m2 + for m in util.to_list(self._alembic_metadata): + m.create_all(self.bind) + + with self.bind.connect() as conn: + ctx_opts = { + "compare_type": True, + "compare_server_default": True, + "target_metadata": model_metadata, + "upgrade_token": "upgrades", + "downgrade_token": "downgrades", + "alembic_module_prefix": "op.", + "sqlalchemy_module_prefix": "sa.", + "include_object": object_filters, + "include_name": name_filters, + "include_schemas": include_schemas, + } + if opts: + ctx_opts.update(opts) + self.context = context = MigrationContext.configure( + connection=conn, opts=ctx_opts + ) + + autogen_context = api.AutogenContext(context, model_metadata) + uo = ops.UpgradeOps(ops=[]) + autogenerate._produce_net_changes(autogen_context, uo) + + if return_ops: + return uo + else: + return uo.as_diffs() + finally: + if max_identifier_length: + dialect = self.bind.dialect + dialect.max_identifier_length = ( + dialect._user_defined_max_identifier_length + ) = existing_length + + def setUp(self): + staging_env() + self.bind = config.db + + def tearDown(self): + if hasattr(self, "_alembic_metadata"): + for m in util.to_list(self._alembic_metadata): + m.drop_all(self.bind) + clear_staging_env() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_comments.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_comments.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef074f57893180048c6193455b0dd1d507c0603 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_comments.py @@ -0,0 +1,242 @@ +from sqlalchemy import Column +from sqlalchemy import Float +from sqlalchemy import MetaData +from sqlalchemy import String +from sqlalchemy import Table + +from ._autogen_fixtures import AutogenFixtureTest +from ...testing import eq_ +from ...testing import mock +from ...testing import TestBase + + +class AutogenerateCommentsTest(AutogenFixtureTest, TestBase): + __backend__ = True + + __requires__ = ("comments",) + + def test_existing_table_comment_no_change(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("test", String(10), primary_key=True), + comment="this is some table", + ) + + Table( + "some_table", + m2, + Column("test", String(10), primary_key=True), + comment="this is some table", + ) + + diffs = self._fixture(m1, m2) + + eq_(diffs, []) + + def test_add_table_comment(self): + m1 = MetaData() + m2 = MetaData() + + Table("some_table", m1, Column("test", String(10), primary_key=True)) + + Table( + "some_table", + m2, + Column("test", String(10), primary_key=True), + comment="this is some table", + ) + + diffs = self._fixture(m1, m2) + + eq_(diffs[0][0], "add_table_comment") + eq_(diffs[0][1].comment, "this is some table") + eq_(diffs[0][2], None) + + def test_remove_table_comment(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("test", String(10), primary_key=True), + comment="this is some table", + ) + + Table("some_table", m2, Column("test", String(10), primary_key=True)) + + diffs = self._fixture(m1, m2) + + eq_(diffs[0][0], "remove_table_comment") + eq_(diffs[0][1].comment, None) + + def test_alter_table_comment(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("test", String(10), primary_key=True), + comment="this is some table", + ) + + Table( + "some_table", + m2, + Column("test", String(10), primary_key=True), + comment="this is also some table", + ) + + diffs = self._fixture(m1, m2) + + eq_(diffs[0][0], "add_table_comment") + eq_(diffs[0][1].comment, "this is also some table") + eq_(diffs[0][2], "this is some table") + + def test_existing_column_comment_no_change(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("test", String(10), primary_key=True), + Column("amount", Float, comment="the amount"), + ) + + Table( + "some_table", + m2, + Column("test", String(10), primary_key=True), + Column("amount", Float, comment="the amount"), + ) + + diffs = self._fixture(m1, m2) + + eq_(diffs, []) + + def test_add_column_comment(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("test", String(10), primary_key=True), + Column("amount", Float), + ) + + Table( + "some_table", + m2, + Column("test", String(10), primary_key=True), + Column("amount", Float, comment="the amount"), + ) + + diffs = self._fixture(m1, m2) + eq_( + diffs, + [ + [ + ( + "modify_comment", + None, + "some_table", + "amount", + { + "existing_nullable": True, + "existing_type": mock.ANY, + "existing_server_default": False, + }, + None, + "the amount", + ) + ] + ], + ) + + def test_remove_column_comment(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("test", String(10), primary_key=True), + Column("amount", Float, comment="the amount"), + ) + + Table( + "some_table", + m2, + Column("test", String(10), primary_key=True), + Column("amount", Float), + ) + + diffs = self._fixture(m1, m2) + eq_( + diffs, + [ + [ + ( + "modify_comment", + None, + "some_table", + "amount", + { + "existing_nullable": True, + "existing_type": mock.ANY, + "existing_server_default": False, + }, + "the amount", + None, + ) + ] + ], + ) + + def test_alter_column_comment(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("test", String(10), primary_key=True), + Column("amount", Float, comment="the amount"), + ) + + Table( + "some_table", + m2, + Column("test", String(10), primary_key=True), + Column("amount", Float, comment="the adjusted amount"), + ) + + diffs = self._fixture(m1, m2) + + eq_( + diffs, + [ + [ + ( + "modify_comment", + None, + "some_table", + "amount", + { + "existing_nullable": True, + "existing_type": mock.ANY, + "existing_server_default": False, + }, + "the amount", + "the adjusted amount", + ) + ] + ], + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_computed.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_computed.py new file mode 100644 index 0000000000000000000000000000000000000000..01a89a1fe85422cc5c4dcfca92d7571040b97d16 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_computed.py @@ -0,0 +1,203 @@ +import sqlalchemy as sa +from sqlalchemy import Column +from sqlalchemy import Integer +from sqlalchemy import MetaData +from sqlalchemy import Table + +from ._autogen_fixtures import AutogenFixtureTest +from ... import testing +from ...testing import config +from ...testing import eq_ +from ...testing import exclusions +from ...testing import is_ +from ...testing import is_true +from ...testing import mock +from ...testing import TestBase + + +class AutogenerateComputedTest(AutogenFixtureTest, TestBase): + __requires__ = ("computed_columns",) + __backend__ = True + + def test_add_computed_column(self): + m1 = MetaData() + m2 = MetaData() + + Table("user", m1, Column("id", Integer, primary_key=True)) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("foo", Integer, sa.Computed("5")), + ) + + diffs = self._fixture(m1, m2) + + eq_(diffs[0][0], "add_column") + eq_(diffs[0][2], "user") + eq_(diffs[0][3].name, "foo") + c = diffs[0][3].computed + + is_true(isinstance(c, sa.Computed)) + is_(c.persisted, None) + eq_(str(c.sqltext), "5") + + def test_remove_computed_column(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("foo", Integer, sa.Computed("5")), + ) + + Table("user", m2, Column("id", Integer, primary_key=True)) + + diffs = self._fixture(m1, m2) + + eq_(diffs[0][0], "remove_column") + eq_(diffs[0][2], "user") + c = diffs[0][3] + eq_(c.name, "foo") + + if config.requirements.computed_reflects_normally.enabled: + is_true(isinstance(c.computed, sa.Computed)) + else: + is_(c.computed, None) + + if config.requirements.computed_reflects_as_server_default.enabled: + is_true(isinstance(c.server_default, sa.DefaultClause)) + eq_(str(c.server_default.arg.text), "5") + elif config.requirements.computed_reflects_normally.enabled: + is_true(isinstance(c.computed, sa.Computed)) + else: + is_(c.computed, None) + + @testing.combinations( + lambda: (None, sa.Computed("bar*5")), + (lambda: (sa.Computed("bar*5"), None)), + lambda: ( + sa.Computed("bar*5"), + sa.Computed("bar * 42", persisted=True), + ), + lambda: (sa.Computed("bar*5"), sa.Computed("bar * 42")), + ) + @config.requirements.computed_reflects_normally + def test_cant_change_computed_warning(self, test_case): + arg_before, arg_after = testing.resolve_lambda(test_case, **locals()) + m1 = MetaData() + m2 = MetaData() + + arg_before = [] if arg_before is None else [arg_before] + arg_after = [] if arg_after is None else [arg_after] + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("bar", Integer), + Column("foo", Integer, *arg_before), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("bar", Integer), + Column("foo", Integer, *arg_after), + ) + + with mock.patch("alembic.util.warn") as mock_warn: + diffs = self._fixture(m1, m2) + + eq_( + mock_warn.mock_calls, + [mock.call("Computed default on user.foo cannot be modified")], + ) + + eq_(list(diffs), []) + + @testing.combinations( + lambda: (None, None), + lambda: (sa.Computed("5"), sa.Computed("5")), + lambda: (sa.Computed("bar*5"), sa.Computed("bar*5")), + ( + lambda: (sa.Computed("bar*5"), None), + config.requirements.computed_doesnt_reflect_as_server_default, + ), + ) + def test_computed_unchanged(self, test_case): + arg_before, arg_after = testing.resolve_lambda(test_case, **locals()) + m1 = MetaData() + m2 = MetaData() + + arg_before = [] if arg_before is None else [arg_before] + arg_after = [] if arg_after is None else [arg_after] + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("bar", Integer), + Column("foo", Integer, *arg_before), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("bar", Integer), + Column("foo", Integer, *arg_after), + ) + + with mock.patch("alembic.util.warn") as mock_warn: + diffs = self._fixture(m1, m2) + eq_(mock_warn.mock_calls, []) + + eq_(list(diffs), []) + + @config.requirements.computed_reflects_as_server_default + def test_remove_computed_default_on_computed(self): + """Asserts the current behavior which is that on PG and Oracle, + the GENERATED ALWAYS AS is reflected as a server default which we can't + tell is actually "computed", so these come out as a modification to + the server default. + + """ + m1 = MetaData() + m2 = MetaData() + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("bar", Integer), + Column("foo", Integer, sa.Computed("bar + 42")), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("bar", Integer), + Column("foo", Integer), + ) + + diffs = self._fixture(m1, m2) + + eq_(diffs[0][0][0], "modify_default") + eq_(diffs[0][0][2], "user") + eq_(diffs[0][0][3], "foo") + old = diffs[0][0][-2] + new = diffs[0][0][-1] + + is_(new, None) + is_true(isinstance(old, sa.DefaultClause)) + + if exclusions.against(config, "postgresql"): + eq_(str(old.arg.text), "(bar + 42)") + elif exclusions.against(config, "oracle"): + eq_(str(old.arg.text), '"BAR"+42') diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_diffs.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_diffs.py new file mode 100644 index 0000000000000000000000000000000000000000..75bcd37aeec53d4afb2447a0f7aaf8ab5ef4c160 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_diffs.py @@ -0,0 +1,273 @@ +from sqlalchemy import BigInteger +from sqlalchemy import Column +from sqlalchemy import Integer +from sqlalchemy import MetaData +from sqlalchemy import Table +from sqlalchemy.testing import in_ + +from ._autogen_fixtures import AutogenFixtureTest +from ... import testing +from ...testing import config +from ...testing import eq_ +from ...testing import is_ +from ...testing import TestBase + + +class AlterColumnTest(AutogenFixtureTest, TestBase): + __backend__ = True + + @testing.combinations((True,), (False,)) + @config.requirements.comments + def test_all_existings_filled(self, pk): + m1 = MetaData() + m2 = MetaData() + + Table("a", m1, Column("x", Integer, primary_key=pk)) + Table("a", m2, Column("x", Integer, comment="x", primary_key=pk)) + + alter_col = self._assert_alter_col(m1, m2, pk) + eq_(alter_col.modify_comment, "x") + + @testing.combinations((True,), (False,)) + @config.requirements.comments + def test_all_existings_filled_in_notnull(self, pk): + m1 = MetaData() + m2 = MetaData() + + Table("a", m1, Column("x", Integer, nullable=False, primary_key=pk)) + Table( + "a", + m2, + Column("x", Integer, nullable=False, comment="x", primary_key=pk), + ) + + self._assert_alter_col(m1, m2, pk, nullable=False) + + @testing.combinations((True,), (False,)) + @config.requirements.comments + def test_all_existings_filled_in_comment(self, pk): + m1 = MetaData() + m2 = MetaData() + + Table("a", m1, Column("x", Integer, comment="old", primary_key=pk)) + Table("a", m2, Column("x", Integer, comment="new", primary_key=pk)) + + alter_col = self._assert_alter_col(m1, m2, pk) + eq_(alter_col.existing_comment, "old") + + @testing.combinations((True,), (False,)) + @config.requirements.comments + def test_all_existings_filled_in_server_default(self, pk): + m1 = MetaData() + m2 = MetaData() + + Table( + "a", m1, Column("x", Integer, server_default="5", primary_key=pk) + ) + Table( + "a", + m2, + Column( + "x", Integer, server_default="5", comment="new", primary_key=pk + ), + ) + + alter_col = self._assert_alter_col(m1, m2, pk) + in_("5", alter_col.existing_server_default.arg.text) + + def _assert_alter_col(self, m1, m2, pk, nullable=None): + ops = self._fixture(m1, m2, return_ops=True) + modify_table = ops.ops[-1] + alter_col = modify_table.ops[0] + + if nullable is None: + eq_(alter_col.existing_nullable, not pk) + else: + eq_(alter_col.existing_nullable, nullable) + assert alter_col.existing_type._compare_type_affinity(Integer()) + return alter_col + + +class AutoincrementTest(AutogenFixtureTest, TestBase): + __backend__ = True + __requires__ = ("integer_subtype_comparisons",) + + def test_alter_column_autoincrement_none(self): + m1 = MetaData() + m2 = MetaData() + + Table("a", m1, Column("x", Integer, nullable=False)) + Table("a", m2, Column("x", Integer, nullable=True)) + + ops = self._fixture(m1, m2, return_ops=True) + assert "autoincrement" not in ops.ops[0].ops[0].kw + + def test_alter_column_autoincrement_pk_false(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "a", + m1, + Column("x", Integer, primary_key=True, autoincrement=False), + ) + Table( + "a", + m2, + Column("x", BigInteger, primary_key=True, autoincrement=False), + ) + + ops = self._fixture(m1, m2, return_ops=True) + is_(ops.ops[0].ops[0].kw["autoincrement"], False) + + def test_alter_column_autoincrement_pk_implicit_true(self): + m1 = MetaData() + m2 = MetaData() + + Table("a", m1, Column("x", Integer, primary_key=True)) + Table("a", m2, Column("x", BigInteger, primary_key=True)) + + ops = self._fixture(m1, m2, return_ops=True) + is_(ops.ops[0].ops[0].kw["autoincrement"], True) + + def test_alter_column_autoincrement_pk_explicit_true(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "a", m1, Column("x", Integer, primary_key=True, autoincrement=True) + ) + Table( + "a", + m2, + Column("x", BigInteger, primary_key=True, autoincrement=True), + ) + + ops = self._fixture(m1, m2, return_ops=True) + is_(ops.ops[0].ops[0].kw["autoincrement"], True) + + def test_alter_column_autoincrement_nonpk_false(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "a", + m1, + Column("id", Integer, primary_key=True), + Column("x", Integer, autoincrement=False), + ) + Table( + "a", + m2, + Column("id", Integer, primary_key=True), + Column("x", BigInteger, autoincrement=False), + ) + + ops = self._fixture(m1, m2, return_ops=True) + is_(ops.ops[0].ops[0].kw["autoincrement"], False) + + def test_alter_column_autoincrement_nonpk_implicit_false(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "a", + m1, + Column("id", Integer, primary_key=True), + Column("x", Integer), + ) + Table( + "a", + m2, + Column("id", Integer, primary_key=True), + Column("x", BigInteger), + ) + + ops = self._fixture(m1, m2, return_ops=True) + assert "autoincrement" not in ops.ops[0].ops[0].kw + + def test_alter_column_autoincrement_nonpk_explicit_true(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "a", + m1, + Column("id", Integer, primary_key=True, autoincrement=False), + Column("x", Integer, autoincrement=True), + ) + Table( + "a", + m2, + Column("id", Integer, primary_key=True, autoincrement=False), + Column("x", BigInteger, autoincrement=True), + ) + + ops = self._fixture(m1, m2, return_ops=True) + is_(ops.ops[0].ops[0].kw["autoincrement"], True) + + def test_alter_column_autoincrement_compositepk_false(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "a", + m1, + Column("id", Integer, primary_key=True), + Column("x", Integer, primary_key=True, autoincrement=False), + ) + Table( + "a", + m2, + Column("id", Integer, primary_key=True), + Column("x", BigInteger, primary_key=True, autoincrement=False), + ) + + ops = self._fixture(m1, m2, return_ops=True) + is_(ops.ops[0].ops[0].kw["autoincrement"], False) + + def test_alter_column_autoincrement_compositepk_implicit_false(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "a", + m1, + Column("id", Integer, primary_key=True), + Column("x", Integer, primary_key=True), + ) + Table( + "a", + m2, + Column("id", Integer, primary_key=True), + Column("x", BigInteger, primary_key=True), + ) + + ops = self._fixture(m1, m2, return_ops=True) + assert "autoincrement" not in ops.ops[0].ops[0].kw + + @config.requirements.autoincrement_on_composite_pk + def test_alter_column_autoincrement_compositepk_explicit_true(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "a", + m1, + Column("id", Integer, primary_key=True, autoincrement=False), + Column("x", Integer, primary_key=True, autoincrement=True), + # on SQLA 1.0 and earlier, this being present + # trips the "add KEY for the primary key" so that the + # AUTO_INCREMENT keyword is accepted by MySQL. SQLA 1.1 and + # greater the columns are just reorganized. + mysql_engine="InnoDB", + ) + Table( + "a", + m2, + Column("id", Integer, primary_key=True, autoincrement=False), + Column("x", BigInteger, primary_key=True, autoincrement=True), + ) + + ops = self._fixture(m1, m2, return_ops=True) + is_(ops.ops[0].ops[0].kw["autoincrement"], True) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_fks.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_fks.py new file mode 100644 index 0000000000000000000000000000000000000000..0240b98d3872bad0d123493a97ccb4b30dbbb709 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_fks.py @@ -0,0 +1,1190 @@ +from sqlalchemy import Column +from sqlalchemy import ForeignKeyConstraint +from sqlalchemy import Integer +from sqlalchemy import MetaData +from sqlalchemy import String +from sqlalchemy import Table + +from ._autogen_fixtures import AutogenFixtureTest +from ...testing import combinations +from ...testing import config +from ...testing import eq_ +from ...testing import mock +from ...testing import TestBase + + +class AutogenerateForeignKeysTest(AutogenFixtureTest, TestBase): + __backend__ = True + __requires__ = ("foreign_key_constraint_reflection",) + + def test_remove_fk(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("test", String(10), primary_key=True), + ) + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("test2", String(10)), + ForeignKeyConstraint(["test2"], ["some_table.test"]), + ) + + Table( + "some_table", + m2, + Column("test", String(10), primary_key=True), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("test2", String(10)), + ) + + diffs = self._fixture(m1, m2) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["test2"], + "some_table", + ["test"], + conditional_name="servergenerated", + ) + + def test_add_fk(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("id", Integer, primary_key=True), + Column("test", String(10)), + ) + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("test2", String(10)), + ) + + Table( + "some_table", + m2, + Column("id", Integer, primary_key=True), + Column("test", String(10)), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("test2", String(10)), + ForeignKeyConstraint(["test2"], ["some_table.test"]), + ) + + diffs = self._fixture(m1, m2) + + self._assert_fk_diff( + diffs[0], "add_fk", "user", ["test2"], "some_table", ["test"] + ) + + def test_no_change(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("id", Integer, primary_key=True), + Column("test", String(10)), + ) + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("test2", Integer), + ForeignKeyConstraint(["test2"], ["some_table.id"]), + ) + + Table( + "some_table", + m2, + Column("id", Integer, primary_key=True), + Column("test", String(10)), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("test2", Integer), + ForeignKeyConstraint(["test2"], ["some_table.id"]), + ) + + diffs = self._fixture(m1, m2) + + eq_(diffs, []) + + def test_no_change_composite_fk(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("id_1", String(10), primary_key=True), + Column("id_2", String(10), primary_key=True), + ) + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("other_id_1", String(10)), + Column("other_id_2", String(10)), + ForeignKeyConstraint( + ["other_id_1", "other_id_2"], + ["some_table.id_1", "some_table.id_2"], + ), + ) + + Table( + "some_table", + m2, + Column("id_1", String(10), primary_key=True), + Column("id_2", String(10), primary_key=True), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("other_id_1", String(10)), + Column("other_id_2", String(10)), + ForeignKeyConstraint( + ["other_id_1", "other_id_2"], + ["some_table.id_1", "some_table.id_2"], + ), + ) + + diffs = self._fixture(m1, m2) + + eq_(diffs, []) + + def test_casing_convention_changed_so_put_drops_first(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("test", String(10), primary_key=True), + ) + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("test2", String(10)), + ForeignKeyConstraint(["test2"], ["some_table.test"], name="MyFK"), + ) + + Table( + "some_table", + m2, + Column("test", String(10), primary_key=True), + ) + + # foreign key autogen currently does not take "name" into account, + # so change the def just for the purposes of testing the + # add/drop order for now. + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("test2", String(10)), + ForeignKeyConstraint(["a1"], ["some_table.test"], name="myfk"), + ) + + diffs = self._fixture(m1, m2) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["test2"], + "some_table", + ["test"], + name="MyFK" if config.requirements.fk_names.enabled else None, + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["a1"], + "some_table", + ["test"], + name="myfk", + ) + + def test_add_composite_fk_with_name(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("id_1", String(10), primary_key=True), + Column("id_2", String(10), primary_key=True), + ) + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("other_id_1", String(10)), + Column("other_id_2", String(10)), + ) + + Table( + "some_table", + m2, + Column("id_1", String(10), primary_key=True), + Column("id_2", String(10), primary_key=True), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("other_id_1", String(10)), + Column("other_id_2", String(10)), + ForeignKeyConstraint( + ["other_id_1", "other_id_2"], + ["some_table.id_1", "some_table.id_2"], + name="fk_test_name", + ), + ) + + diffs = self._fixture(m1, m2) + self._assert_fk_diff( + diffs[0], + "add_fk", + "user", + ["other_id_1", "other_id_2"], + "some_table", + ["id_1", "id_2"], + name="fk_test_name", + ) + + @config.requirements.no_name_normalize + def test_remove_composite_fk(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("id_1", String(10), primary_key=True), + Column("id_2", String(10), primary_key=True), + ) + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("other_id_1", String(10)), + Column("other_id_2", String(10)), + ForeignKeyConstraint( + ["other_id_1", "other_id_2"], + ["some_table.id_1", "some_table.id_2"], + name="fk_test_name", + ), + ) + + Table( + "some_table", + m2, + Column("id_1", String(10), primary_key=True), + Column("id_2", String(10), primary_key=True), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("a1", String(10), server_default="x"), + Column("other_id_1", String(10)), + Column("other_id_2", String(10)), + ) + + diffs = self._fixture(m1, m2) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["other_id_1", "other_id_2"], + "some_table", + ["id_1", "id_2"], + conditional_name="fk_test_name", + ) + + def test_add_fk_colkeys(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("id_1", String(10), primary_key=True), + Column("id_2", String(10), primary_key=True), + ) + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("other_id_1", String(10)), + Column("other_id_2", String(10)), + ) + + Table( + "some_table", + m2, + Column("id_1", String(10), key="tid1", primary_key=True), + Column("id_2", String(10), key="tid2", primary_key=True), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("other_id_1", String(10), key="oid1"), + Column("other_id_2", String(10), key="oid2"), + ForeignKeyConstraint( + ["oid1", "oid2"], + ["some_table.tid1", "some_table.tid2"], + name="fk_test_name", + ), + ) + + diffs = self._fixture(m1, m2) + + self._assert_fk_diff( + diffs[0], + "add_fk", + "user", + ["other_id_1", "other_id_2"], + "some_table", + ["id_1", "id_2"], + name="fk_test_name", + ) + + def test_no_change_colkeys(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("id_1", String(10), primary_key=True), + Column("id_2", String(10), primary_key=True), + ) + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("other_id_1", String(10)), + Column("other_id_2", String(10)), + ForeignKeyConstraint( + ["other_id_1", "other_id_2"], + ["some_table.id_1", "some_table.id_2"], + ), + ) + + Table( + "some_table", + m2, + Column("id_1", String(10), key="tid1", primary_key=True), + Column("id_2", String(10), key="tid2", primary_key=True), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("other_id_1", String(10), key="oid1"), + Column("other_id_2", String(10), key="oid2"), + ForeignKeyConstraint( + ["oid1", "oid2"], ["some_table.tid1", "some_table.tid2"] + ), + ) + + diffs = self._fixture(m1, m2) + + eq_(diffs, []) + + +class IncludeHooksTest(AutogenFixtureTest, TestBase): + __backend__ = True + __requires__ = ("fk_names",) + + @combinations(("object",), ("name",)) + @config.requirements.no_name_normalize + def test_remove_connection_fk(self, hook_type): + m1 = MetaData() + m2 = MetaData() + + ref = Table( + "ref", + m1, + Column("id", Integer, primary_key=True), + ) + t1 = Table( + "t", + m1, + Column("x", Integer), + Column("y", Integer), + ) + t1.append_constraint( + ForeignKeyConstraint([t1.c.x], [ref.c.id], name="fk1") + ) + t1.append_constraint( + ForeignKeyConstraint([t1.c.y], [ref.c.id], name="fk2") + ) + + ref = Table( + "ref", + m2, + Column("id", Integer, primary_key=True), + ) + Table( + "t", + m2, + Column("x", Integer), + Column("y", Integer), + ) + + if hook_type == "object": + + def include_object(object_, name, type_, reflected, compare_to): + return not ( + isinstance(object_, ForeignKeyConstraint) + and type_ == "foreign_key_constraint" + and reflected + and name == "fk1" + ) + + diffs = self._fixture(m1, m2, object_filters=include_object) + elif hook_type == "name": + + def include_name(name, type_, parent_names): + if name == "fk1": + if type_ == "index": # MariaDB thing + return True + eq_(type_, "foreign_key_constraint") + eq_( + parent_names, + { + "schema_name": None, + "table_name": "t", + "schema_qualified_table_name": "t", + }, + ) + return False + else: + return True + + diffs = self._fixture(m1, m2, name_filters=include_name) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "t", + ["y"], + "ref", + ["id"], + conditional_name="fk2", + ) + eq_(len(diffs), 1) + + def test_add_metadata_fk(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "ref", + m1, + Column("id", Integer, primary_key=True), + ) + Table( + "t", + m1, + Column("x", Integer), + Column("y", Integer), + ) + + ref = Table( + "ref", + m2, + Column("id", Integer, primary_key=True), + ) + t2 = Table( + "t", + m2, + Column("x", Integer), + Column("y", Integer), + ) + t2.append_constraint( + ForeignKeyConstraint([t2.c.x], [ref.c.id], name="fk1") + ) + t2.append_constraint( + ForeignKeyConstraint([t2.c.y], [ref.c.id], name="fk2") + ) + + def include_object(object_, name, type_, reflected, compare_to): + return not ( + isinstance(object_, ForeignKeyConstraint) + and type_ == "foreign_key_constraint" + and not reflected + and name == "fk1" + ) + + diffs = self._fixture(m1, m2, object_filters=include_object) + + self._assert_fk_diff( + diffs[0], "add_fk", "t", ["y"], "ref", ["id"], name="fk2" + ) + eq_(len(diffs), 1) + + @combinations(("object",), ("name",)) + @config.requirements.no_name_normalize + def test_change_fk(self, hook_type): + m1 = MetaData() + m2 = MetaData() + + r1a = Table( + "ref_a", + m1, + Column("a", Integer, primary_key=True), + ) + Table( + "ref_b", + m1, + Column("a", Integer, primary_key=True), + Column("b", Integer, primary_key=True), + ) + t1 = Table( + "t", + m1, + Column("x", Integer), + Column("y", Integer), + Column("z", Integer), + ) + t1.append_constraint( + ForeignKeyConstraint([t1.c.x], [r1a.c.a], name="fk1") + ) + t1.append_constraint( + ForeignKeyConstraint([t1.c.y], [r1a.c.a], name="fk2") + ) + + Table( + "ref_a", + m2, + Column("a", Integer, primary_key=True), + ) + r2b = Table( + "ref_b", + m2, + Column("a", Integer, primary_key=True), + Column("b", Integer, primary_key=True), + ) + t2 = Table( + "t", + m2, + Column("x", Integer), + Column("y", Integer), + Column("z", Integer), + ) + t2.append_constraint( + ForeignKeyConstraint( + [t2.c.x, t2.c.z], [r2b.c.a, r2b.c.b], name="fk1" + ) + ) + t2.append_constraint( + ForeignKeyConstraint( + [t2.c.y, t2.c.z], [r2b.c.a, r2b.c.b], name="fk2" + ) + ) + + if hook_type == "object": + + def include_object(object_, name, type_, reflected, compare_to): + return not ( + isinstance(object_, ForeignKeyConstraint) + and type_ == "foreign_key_constraint" + and name == "fk1" + ) + + diffs = self._fixture(m1, m2, object_filters=include_object) + elif hook_type == "name": + + def include_name(name, type_, parent_names): + if type_ == "index": + return True # MariaDB thing + + if name == "fk1": + eq_(type_, "foreign_key_constraint") + eq_( + parent_names, + { + "schema_name": None, + "table_name": "t", + "schema_qualified_table_name": "t", + }, + ) + return False + else: + return True + + diffs = self._fixture(m1, m2, name_filters=include_name) + + if hook_type == "object": + self._assert_fk_diff( + diffs[0], "remove_fk", "t", ["y"], "ref_a", ["a"], name="fk2" + ) + self._assert_fk_diff( + diffs[1], + "add_fk", + "t", + ["y", "z"], + "ref_b", + ["a", "b"], + name="fk2", + ) + eq_(len(diffs), 2) + elif hook_type == "name": + eq_( + {(d[0], d[1].name) for d in diffs}, + {("add_fk", "fk2"), ("add_fk", "fk1"), ("remove_fk", "fk2")}, + ) + + +class AutogenerateFKOptionsTest(AutogenFixtureTest, TestBase): + __backend__ = True + + def _fk_opts_fixture(self, old_opts, new_opts): + m1 = MetaData() + m2 = MetaData() + + Table( + "some_table", + m1, + Column("id", Integer, primary_key=True), + Column("test", String(10)), + ) + + Table( + "user", + m1, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("tid", Integer), + ForeignKeyConstraint(["tid"], ["some_table.id"], **old_opts), + ) + + Table( + "some_table", + m2, + Column("id", Integer, primary_key=True), + Column("test", String(10)), + ) + + Table( + "user", + m2, + Column("id", Integer, primary_key=True), + Column("name", String(50), nullable=False), + Column("tid", Integer), + ForeignKeyConstraint(["tid"], ["some_table.id"], **new_opts), + ) + + return self._fixture(m1, m2) + + @config.requirements.fk_ondelete_is_reflected + def test_add_ondelete(self): + diffs = self._fk_opts_fixture({}, {"ondelete": "cascade"}) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + ondelete=None, + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + ondelete="cascade", + ) + + @config.requirements.fk_ondelete_is_reflected + def test_remove_ondelete(self): + diffs = self._fk_opts_fixture({"ondelete": "CASCADE"}, {}) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + ondelete="CASCADE", + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + ondelete=None, + ) + + def test_nochange_ondelete(self): + """test case sensitivity""" + diffs = self._fk_opts_fixture( + {"ondelete": "caSCAde"}, {"ondelete": "CasCade"} + ) + eq_(diffs, []) + + @config.requirements.fk_onupdate_is_reflected + def test_add_onupdate(self): + diffs = self._fk_opts_fixture({}, {"onupdate": "cascade"}) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + onupdate=None, + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + onupdate="cascade", + ) + + @config.requirements.fk_onupdate_is_reflected + def test_remove_onupdate(self): + diffs = self._fk_opts_fixture({"onupdate": "CASCADE"}, {}) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + onupdate="CASCADE", + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + onupdate=None, + ) + + @config.requirements.fk_onupdate + def test_nochange_onupdate(self): + """test case sensitivity""" + diffs = self._fk_opts_fixture( + {"onupdate": "caSCAde"}, {"onupdate": "CasCade"} + ) + eq_(diffs, []) + + @config.requirements.fk_ondelete_restrict + def test_nochange_ondelete_restrict(self): + """test the RESTRICT option which MySQL doesn't report on""" + + diffs = self._fk_opts_fixture( + {"ondelete": "restrict"}, {"ondelete": "restrict"} + ) + eq_(diffs, []) + + @config.requirements.fk_onupdate_restrict + def test_nochange_onupdate_restrict(self): + """test the RESTRICT option which MySQL doesn't report on""" + + diffs = self._fk_opts_fixture( + {"onupdate": "restrict"}, {"onupdate": "restrict"} + ) + eq_(diffs, []) + + @config.requirements.fk_ondelete_noaction + def test_nochange_ondelete_noaction(self): + """test the NO ACTION option which generally comes back as None""" + + diffs = self._fk_opts_fixture( + {"ondelete": "no action"}, {"ondelete": "no action"} + ) + eq_(diffs, []) + + @config.requirements.fk_onupdate + def test_nochange_onupdate_noaction(self): + """test the NO ACTION option which generally comes back as None""" + + diffs = self._fk_opts_fixture( + {"onupdate": "no action"}, {"onupdate": "no action"} + ) + eq_(diffs, []) + + @config.requirements.fk_ondelete_restrict + def test_change_ondelete_from_restrict(self): + """test the RESTRICT option which MySQL doesn't report on""" + + # note that this is impossible to detect if we change + # from RESTRICT to NO ACTION on MySQL. + diffs = self._fk_opts_fixture( + {"ondelete": "restrict"}, {"ondelete": "cascade"} + ) + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + onupdate=None, + ondelete=mock.ANY, # MySQL reports None, PG reports RESTRICT + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + onupdate=None, + ondelete="cascade", + ) + + @config.requirements.fk_ondelete_restrict + def test_change_onupdate_from_restrict(self): + """test the RESTRICT option which MySQL doesn't report on""" + + # note that this is impossible to detect if we change + # from RESTRICT to NO ACTION on MySQL. + diffs = self._fk_opts_fixture( + {"onupdate": "restrict"}, {"onupdate": "cascade"} + ) + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + onupdate=mock.ANY, # MySQL reports None, PG reports RESTRICT + ondelete=None, + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + onupdate="cascade", + ondelete=None, + ) + + @config.requirements.fk_ondelete_is_reflected + @config.requirements.fk_onupdate_is_reflected + def test_ondelete_onupdate_combo(self): + diffs = self._fk_opts_fixture( + {"onupdate": "CASCADE", "ondelete": "SET NULL"}, + {"onupdate": "RESTRICT", "ondelete": "RESTRICT"}, + ) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + onupdate="CASCADE", + ondelete="SET NULL", + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + onupdate="RESTRICT", + ondelete="RESTRICT", + ) + + @config.requirements.fk_initially + def test_add_initially_deferred(self): + diffs = self._fk_opts_fixture({}, {"initially": "deferred"}) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + initially=None, + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + initially="deferred", + ) + + @config.requirements.fk_initially + def test_remove_initially_deferred(self): + diffs = self._fk_opts_fixture({"initially": "deferred"}, {}) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + initially="DEFERRED", + deferrable=True, + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + initially=None, + ) + + @config.requirements.fk_deferrable + @config.requirements.fk_initially + def test_add_initially_immediate_plus_deferrable(self): + diffs = self._fk_opts_fixture( + {}, {"initially": "immediate", "deferrable": True} + ) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + initially=None, + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + initially="immediate", + deferrable=True, + ) + + @config.requirements.fk_deferrable + @config.requirements.fk_initially + def test_remove_initially_immediate_plus_deferrable(self): + diffs = self._fk_opts_fixture( + {"initially": "immediate", "deferrable": True}, {} + ) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + initially=None, # immediate is the default + deferrable=True, + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + initially=None, + deferrable=None, + ) + + @config.requirements.fk_initially + @config.requirements.fk_deferrable + def test_add_initially_deferrable_nochange_one(self): + diffs = self._fk_opts_fixture( + {"deferrable": True, "initially": "immediate"}, + {"deferrable": True, "initially": "immediate"}, + ) + + eq_(diffs, []) + + @config.requirements.fk_initially + @config.requirements.fk_deferrable + def test_add_initially_deferrable_nochange_two(self): + diffs = self._fk_opts_fixture( + {"deferrable": True, "initially": "deferred"}, + {"deferrable": True, "initially": "deferred"}, + ) + + eq_(diffs, []) + + @config.requirements.fk_initially + @config.requirements.fk_deferrable + def test_add_initially_deferrable_nochange_three(self): + diffs = self._fk_opts_fixture( + {"deferrable": None, "initially": "deferred"}, + {"deferrable": None, "initially": "deferred"}, + ) + + eq_(diffs, []) + + @config.requirements.fk_deferrable + def test_add_deferrable(self): + diffs = self._fk_opts_fixture({}, {"deferrable": True}) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + deferrable=None, + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + deferrable=True, + ) + + @config.requirements.fk_deferrable_is_reflected + def test_remove_deferrable(self): + diffs = self._fk_opts_fixture({"deferrable": True}, {}) + + self._assert_fk_diff( + diffs[0], + "remove_fk", + "user", + ["tid"], + "some_table", + ["id"], + deferrable=True, + conditional_name="servergenerated", + ) + + self._assert_fk_diff( + diffs[1], + "add_fk", + "user", + ["tid"], + "some_table", + ["id"], + deferrable=None, + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_identity.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_identity.py new file mode 100644 index 0000000000000000000000000000000000000000..3dee9fc9903f74fd06adfaa837f22af51ec6dcd1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_autogen_identity.py @@ -0,0 +1,226 @@ +import sqlalchemy as sa +from sqlalchemy import Column +from sqlalchemy import Integer +from sqlalchemy import MetaData +from sqlalchemy import Table + +from alembic.util import sqla_compat +from ._autogen_fixtures import AutogenFixtureTest +from ... import testing +from ...testing import config +from ...testing import eq_ +from ...testing import is_true +from ...testing import TestBase + + +class AutogenerateIdentityTest(AutogenFixtureTest, TestBase): + __requires__ = ("identity_columns",) + __backend__ = True + + def test_add_identity_column(self): + m1 = MetaData() + m2 = MetaData() + + Table("user", m1, Column("other", sa.Text)) + + Table( + "user", + m2, + Column("other", sa.Text), + Column( + "id", + Integer, + sa.Identity(start=5, increment=7), + primary_key=True, + ), + ) + + diffs = self._fixture(m1, m2) + + eq_(diffs[0][0], "add_column") + eq_(diffs[0][2], "user") + eq_(diffs[0][3].name, "id") + i = diffs[0][3].identity + + is_true(isinstance(i, sa.Identity)) + eq_(i.start, 5) + eq_(i.increment, 7) + + def test_remove_identity_column(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "user", + m1, + Column( + "id", + Integer, + sa.Identity(start=2, increment=3), + primary_key=True, + ), + ) + + Table("user", m2) + + diffs = self._fixture(m1, m2) + + eq_(diffs[0][0], "remove_column") + eq_(diffs[0][2], "user") + c = diffs[0][3] + eq_(c.name, "id") + + is_true(isinstance(c.identity, sa.Identity)) + eq_(c.identity.start, 2) + eq_(c.identity.increment, 3) + + def test_no_change_identity_column(self): + m1 = MetaData() + m2 = MetaData() + + for m in (m1, m2): + id_ = sa.Identity(start=2) + Table("user", m, Column("id", Integer, id_)) + + diffs = self._fixture(m1, m2) + + eq_(diffs, []) + + def test_dialect_kwargs_changes(self): + m1 = MetaData() + m2 = MetaData() + + if sqla_compat.identity_has_dialect_kwargs: + args = {"oracle_on_null": True, "oracle_order": True} + else: + args = {"on_null": True, "order": True} + + Table("user", m1, Column("id", Integer, sa.Identity(start=2))) + id_ = sa.Identity(start=2, **args) + Table("user", m2, Column("id", Integer, id_)) + + diffs = self._fixture(m1, m2) + if config.db.name == "oracle": + is_true(len(diffs), 1) + eq_(diffs[0][0][0], "modify_default") + else: + eq_(diffs, []) + + @testing.combinations( + (None, dict(start=2)), + (dict(start=2), None), + (dict(start=2), dict(start=2, increment=7)), + (dict(always=False), dict(always=True)), + ( + dict(start=1, minvalue=0, maxvalue=100, cycle=True), + dict(start=1, minvalue=0, maxvalue=100, cycle=False), + ), + ( + dict(start=10, increment=3, maxvalue=9999), + dict(start=10, increment=1, maxvalue=3333), + ), + ) + @config.requirements.identity_columns_alter + def test_change_identity(self, before, after): + arg_before = (sa.Identity(**before),) if before else () + arg_after = (sa.Identity(**after),) if after else () + + m1 = MetaData() + m2 = MetaData() + + Table( + "user", + m1, + Column("id", Integer, *arg_before), + Column("other", sa.Text), + ) + + Table( + "user", + m2, + Column("id", Integer, *arg_after), + Column("other", sa.Text), + ) + + diffs = self._fixture(m1, m2) + + eq_(len(diffs[0]), 1) + diffs = diffs[0][0] + eq_(diffs[0], "modify_default") + eq_(diffs[2], "user") + eq_(diffs[3], "id") + old = diffs[5] + new = diffs[6] + + def check(kw, idt): + if kw: + is_true(isinstance(idt, sa.Identity)) + for k, v in kw.items(): + eq_(getattr(idt, k), v) + else: + is_true(idt in (None, False)) + + check(before, old) + check(after, new) + + def test_add_identity_to_column(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "user", + m1, + Column("id", Integer), + Column("other", sa.Text), + ) + + Table( + "user", + m2, + Column("id", Integer, sa.Identity(start=2, maxvalue=1000)), + Column("other", sa.Text), + ) + + diffs = self._fixture(m1, m2) + + eq_(len(diffs[0]), 1) + diffs = diffs[0][0] + eq_(diffs[0], "modify_default") + eq_(diffs[2], "user") + eq_(diffs[3], "id") + eq_(diffs[5], None) + added = diffs[6] + + is_true(isinstance(added, sa.Identity)) + eq_(added.start, 2) + eq_(added.maxvalue, 1000) + + def test_remove_identity_from_column(self): + m1 = MetaData() + m2 = MetaData() + + Table( + "user", + m1, + Column("id", Integer, sa.Identity(start=2, maxvalue=1000)), + Column("other", sa.Text), + ) + + Table( + "user", + m2, + Column("id", Integer), + Column("other", sa.Text), + ) + + diffs = self._fixture(m1, m2) + + eq_(len(diffs[0]), 1) + diffs = diffs[0][0] + eq_(diffs[0], "modify_default") + eq_(diffs[2], "user") + eq_(diffs[3], "id") + eq_(diffs[6], None) + removed = diffs[5] + + is_true(isinstance(removed, sa.Identity)) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_environment.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..8c86859ae2cff2b0497593dff6fc547a2487bbe3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_environment.py @@ -0,0 +1,364 @@ +import io + +from ...migration import MigrationContext +from ...testing import assert_raises +from ...testing import config +from ...testing import eq_ +from ...testing import is_ +from ...testing import is_false +from ...testing import is_not_ +from ...testing import is_true +from ...testing import ne_ +from ...testing.fixtures import TestBase + + +class MigrationTransactionTest(TestBase): + __backend__ = True + + conn = None + + def _fixture(self, opts): + self.conn = conn = config.db.connect() + + if opts.get("as_sql", False): + self.context = MigrationContext.configure( + dialect=conn.dialect, opts=opts + ) + self.context.output_buffer = ( + self.context.impl.output_buffer + ) = io.StringIO() + else: + self.context = MigrationContext.configure( + connection=conn, opts=opts + ) + return self.context + + def teardown_method(self): + if self.conn: + self.conn.close() + + def test_proxy_transaction_rollback(self): + context = self._fixture( + {"transaction_per_migration": True, "transactional_ddl": True} + ) + + is_false(self.conn.in_transaction()) + proxy = context.begin_transaction(_per_migration=True) + is_true(self.conn.in_transaction()) + proxy.rollback() + is_false(self.conn.in_transaction()) + + def test_proxy_transaction_commit(self): + context = self._fixture( + {"transaction_per_migration": True, "transactional_ddl": True} + ) + proxy = context.begin_transaction(_per_migration=True) + is_true(self.conn.in_transaction()) + proxy.commit() + is_false(self.conn.in_transaction()) + + def test_proxy_transaction_contextmanager_commit(self): + context = self._fixture( + {"transaction_per_migration": True, "transactional_ddl": True} + ) + proxy = context.begin_transaction(_per_migration=True) + is_true(self.conn.in_transaction()) + with proxy: + pass + is_false(self.conn.in_transaction()) + + def test_proxy_transaction_contextmanager_rollback(self): + context = self._fixture( + {"transaction_per_migration": True, "transactional_ddl": True} + ) + proxy = context.begin_transaction(_per_migration=True) + is_true(self.conn.in_transaction()) + + def go(): + with proxy: + raise Exception("hi") + + assert_raises(Exception, go) + is_false(self.conn.in_transaction()) + + def test_proxy_transaction_contextmanager_explicit_rollback(self): + context = self._fixture( + {"transaction_per_migration": True, "transactional_ddl": True} + ) + proxy = context.begin_transaction(_per_migration=True) + is_true(self.conn.in_transaction()) + + with proxy: + is_true(self.conn.in_transaction()) + proxy.rollback() + is_false(self.conn.in_transaction()) + + is_false(self.conn.in_transaction()) + + def test_proxy_transaction_contextmanager_explicit_commit(self): + context = self._fixture( + {"transaction_per_migration": True, "transactional_ddl": True} + ) + proxy = context.begin_transaction(_per_migration=True) + is_true(self.conn.in_transaction()) + + with proxy: + is_true(self.conn.in_transaction()) + proxy.commit() + is_false(self.conn.in_transaction()) + + is_false(self.conn.in_transaction()) + + def test_transaction_per_migration_transactional_ddl(self): + context = self._fixture( + {"transaction_per_migration": True, "transactional_ddl": True} + ) + + is_false(self.conn.in_transaction()) + + with context.begin_transaction(): + is_false(self.conn.in_transaction()) + with context.begin_transaction(_per_migration=True): + is_true(self.conn.in_transaction()) + + is_false(self.conn.in_transaction()) + is_false(self.conn.in_transaction()) + + def test_transaction_per_migration_non_transactional_ddl(self): + context = self._fixture( + {"transaction_per_migration": True, "transactional_ddl": False} + ) + + is_false(self.conn.in_transaction()) + + with context.begin_transaction(): + is_false(self.conn.in_transaction()) + with context.begin_transaction(_per_migration=True): + is_true(self.conn.in_transaction()) + + is_false(self.conn.in_transaction()) + is_false(self.conn.in_transaction()) + + def test_transaction_per_all_transactional_ddl(self): + context = self._fixture({"transactional_ddl": True}) + + is_false(self.conn.in_transaction()) + + with context.begin_transaction(): + is_true(self.conn.in_transaction()) + with context.begin_transaction(_per_migration=True): + is_true(self.conn.in_transaction()) + + is_true(self.conn.in_transaction()) + is_false(self.conn.in_transaction()) + + def test_transaction_per_all_non_transactional_ddl(self): + context = self._fixture({"transactional_ddl": False}) + + is_false(self.conn.in_transaction()) + + with context.begin_transaction(): + is_false(self.conn.in_transaction()) + with context.begin_transaction(_per_migration=True): + is_true(self.conn.in_transaction()) + + is_false(self.conn.in_transaction()) + is_false(self.conn.in_transaction()) + + def test_transaction_per_all_sqlmode(self): + context = self._fixture({"as_sql": True}) + + context.execute("step 1") + with context.begin_transaction(): + context.execute("step 2") + with context.begin_transaction(_per_migration=True): + context.execute("step 3") + + context.execute("step 4") + context.execute("step 5") + + if context.impl.transactional_ddl: + self._assert_impl_steps( + "step 1", + "BEGIN", + "step 2", + "step 3", + "step 4", + "COMMIT", + "step 5", + ) + else: + self._assert_impl_steps( + "step 1", "step 2", "step 3", "step 4", "step 5" + ) + + def test_transaction_per_migration_sqlmode(self): + context = self._fixture( + {"as_sql": True, "transaction_per_migration": True} + ) + + context.execute("step 1") + with context.begin_transaction(): + context.execute("step 2") + with context.begin_transaction(_per_migration=True): + context.execute("step 3") + + context.execute("step 4") + context.execute("step 5") + + if context.impl.transactional_ddl: + self._assert_impl_steps( + "step 1", + "step 2", + "BEGIN", + "step 3", + "COMMIT", + "step 4", + "step 5", + ) + else: + self._assert_impl_steps( + "step 1", "step 2", "step 3", "step 4", "step 5" + ) + + @config.requirements.autocommit_isolation + def test_autocommit_block(self): + context = self._fixture({"transaction_per_migration": True}) + + is_false(self.conn.in_transaction()) + + with context.begin_transaction(): + is_false(self.conn.in_transaction()) + with context.begin_transaction(_per_migration=True): + is_true(self.conn.in_transaction()) + + with context.autocommit_block(): + # in 1.x, self.conn is separate due to the + # execution_options call. however for future they are the + # same connection and there is a "transaction" block + # despite autocommit + if self.is_sqlalchemy_future: + is_(context.connection, self.conn) + else: + is_not_(context.connection, self.conn) + is_false(self.conn.in_transaction()) + + eq_( + context.connection._execution_options[ + "isolation_level" + ], + "AUTOCOMMIT", + ) + + ne_( + context.connection._execution_options.get( + "isolation_level", None + ), + "AUTOCOMMIT", + ) + is_true(self.conn.in_transaction()) + + is_false(self.conn.in_transaction()) + is_false(self.conn.in_transaction()) + + @config.requirements.autocommit_isolation + def test_autocommit_block_no_transaction(self): + context = self._fixture({"transaction_per_migration": True}) + + is_false(self.conn.in_transaction()) + + with context.autocommit_block(): + is_true(context.connection.in_transaction()) + + # in 1.x, self.conn is separate due to the execution_options + # call. however for future they are the same connection and there + # is a "transaction" block despite autocommit + if self.is_sqlalchemy_future: + is_(context.connection, self.conn) + else: + is_not_(context.connection, self.conn) + is_false(self.conn.in_transaction()) + + eq_( + context.connection._execution_options["isolation_level"], + "AUTOCOMMIT", + ) + + ne_( + context.connection._execution_options.get("isolation_level", None), + "AUTOCOMMIT", + ) + + is_false(self.conn.in_transaction()) + + def test_autocommit_block_transactional_ddl_sqlmode(self): + context = self._fixture( + { + "transaction_per_migration": True, + "transactional_ddl": True, + "as_sql": True, + } + ) + + with context.begin_transaction(): + context.execute("step 1") + with context.begin_transaction(_per_migration=True): + context.execute("step 2") + + with context.autocommit_block(): + context.execute("step 3") + + context.execute("step 4") + + context.execute("step 5") + + self._assert_impl_steps( + "step 1", + "BEGIN", + "step 2", + "COMMIT", + "step 3", + "BEGIN", + "step 4", + "COMMIT", + "step 5", + ) + + def test_autocommit_block_nontransactional_ddl_sqlmode(self): + context = self._fixture( + { + "transaction_per_migration": True, + "transactional_ddl": False, + "as_sql": True, + } + ) + + with context.begin_transaction(): + context.execute("step 1") + with context.begin_transaction(_per_migration=True): + context.execute("step 2") + + with context.autocommit_block(): + context.execute("step 3") + + context.execute("step 4") + + context.execute("step 5") + + self._assert_impl_steps( + "step 1", "step 2", "step 3", "step 4", "step 5" + ) + + def _assert_impl_steps(self, *steps): + to_check = self.context.output_buffer.getvalue() + + self.context.impl.output_buffer = buf = io.StringIO() + for step in steps: + if step == "BEGIN": + self.context.impl.emit_begin() + elif step == "COMMIT": + self.context.impl.emit_commit() + else: + self.context.impl._exec(step) + + eq_(to_check, buf.getvalue()) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_op.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_op.py new file mode 100644 index 0000000000000000000000000000000000000000..a63b3f2f9f2a7bfd879e5b06a05f0c6a64277b8f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/suite/test_op.py @@ -0,0 +1,42 @@ +"""Test against the builders in the op.* module.""" + +from sqlalchemy import Column +from sqlalchemy import event +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy import Table +from sqlalchemy.sql import text + +from ...testing.fixtures import AlterColRoundTripFixture +from ...testing.fixtures import TestBase + + +@event.listens_for(Table, "after_parent_attach") +def _add_cols(table, metadata): + if table.name == "tbl_with_auto_appended_column": + table.append_column(Column("bat", Integer)) + + +class BackendAlterColumnTest(AlterColRoundTripFixture, TestBase): + __backend__ = True + + def test_rename_column(self): + self._run_alter_col({}, {"name": "newname"}) + + def test_modify_type_int_str(self): + self._run_alter_col({"type": Integer()}, {"type": String(50)}) + + def test_add_server_default_int(self): + self._run_alter_col({"type": Integer}, {"server_default": text("5")}) + + def test_modify_server_default_int(self): + self._run_alter_col( + {"type": Integer, "server_default": text("2")}, + {"server_default": text("5")}, + ) + + def test_modify_nullable_to_non(self): + self._run_alter_col({}, {"nullable": False}) + + def test_modify_non_nullable_to_nullable(self): + self._run_alter_col({"nullable": False}, {"nullable": True}) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/util.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/util.py new file mode 100644 index 0000000000000000000000000000000000000000..4517a69f6b5c4ebdc34702005074e83178cc9d95 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/util.py @@ -0,0 +1,126 @@ +# testing/util.py +# Copyright (C) 2005-2019 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php +from __future__ import annotations + +import types +from typing import Union + +from sqlalchemy.util import inspect_getfullargspec + +from ..util import sqla_2 + + +def flag_combinations(*combinations): + """A facade around @testing.combinations() oriented towards boolean + keyword-based arguments. + + Basically generates a nice looking identifier based on the keywords + and also sets up the argument names. + + E.g.:: + + @testing.flag_combinations( + dict(lazy=False, passive=False), + dict(lazy=True, passive=False), + dict(lazy=False, passive=True), + dict(lazy=False, passive=True, raiseload=True), + ) + + + would result in:: + + @testing.combinations( + ('', False, False, False), + ('lazy', True, False, False), + ('lazy_passive', True, True, False), + ('lazy_passive', True, True, True), + id_='iaaa', + argnames='lazy,passive,raiseload' + ) + + """ + from sqlalchemy.testing import config + + keys = set() + + for d in combinations: + keys.update(d) + + keys = sorted(keys) + + return config.combinations( + *[ + ("_".join(k for k in keys if d.get(k, False)),) + + tuple(d.get(k, False) for k in keys) + for d in combinations + ], + id_="i" + ("a" * len(keys)), + argnames=",".join(keys), + ) + + +def resolve_lambda(__fn, **kw): + """Given a no-arg lambda and a namespace, return a new lambda that + has all the values filled in. + + This is used so that we can have module-level fixtures that + refer to instance-level variables using lambdas. + + """ + + pos_args = inspect_getfullargspec(__fn)[0] + pass_pos_args = {arg: kw.pop(arg) for arg in pos_args} + glb = dict(__fn.__globals__) + glb.update(kw) + new_fn = types.FunctionType(__fn.__code__, glb) + return new_fn(**pass_pos_args) + + +def metadata_fixture(ddl="function"): + """Provide MetaData for a pytest fixture.""" + + from sqlalchemy.testing import config + from . import fixture_functions + + def decorate(fn): + def run_ddl(self): + from sqlalchemy import schema + + metadata = self.metadata = schema.MetaData() + try: + result = fn(self, metadata) + metadata.create_all(config.db) + # TODO: + # somehow get a per-function dml erase fixture here + yield result + finally: + metadata.drop_all(config.db) + + return fixture_functions.fixture(scope=ddl)(run_ddl) + + return decorate + + +def _safe_int(value: str) -> Union[int, str]: + try: + return int(value) + except: + return value + + +def testing_engine(url=None, options=None, future=False): + from sqlalchemy.testing import config + from sqlalchemy.testing.engines import testing_engine + + if not future: + future = getattr(config._current.options, "future_engine", False) + + if not sqla_2: + kw = {"future": future} if future else {} + else: + kw = {} + return testing_engine(url, options, **kw) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/warnings.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..e87136b85f380dbc741ee7f860740d3423bab383 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/testing/warnings.py @@ -0,0 +1,40 @@ +# testing/warnings.py +# Copyright (C) 2005-2021 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php + + +import warnings + +from sqlalchemy import exc as sa_exc + +from ..util import sqla_14 + + +def setup_filters(): + """Set global warning behavior for the test suite.""" + + warnings.resetwarnings() + + warnings.filterwarnings("error", category=sa_exc.SADeprecationWarning) + warnings.filterwarnings("error", category=sa_exc.SAWarning) + + # some selected deprecations... + warnings.filterwarnings("error", category=DeprecationWarning) + if not sqla_14: + # 1.3 uses pkg_resources in PluginLoader + warnings.filterwarnings( + "ignore", + "pkg_resources is deprecated as an API", + DeprecationWarning, + ) + try: + import pytest + except ImportError: + pass + else: + warnings.filterwarnings( + "once", category=pytest.PytestDeprecationWarning + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4724e1f0847c4b8fe942e85285970c117acfa915 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/__init__.py @@ -0,0 +1,35 @@ +from .editor import open_in_editor as open_in_editor +from .exc import AutogenerateDiffsDetected as AutogenerateDiffsDetected +from .exc import CommandError as CommandError +from .langhelpers import _with_legacy_names as _with_legacy_names +from .langhelpers import asbool as asbool +from .langhelpers import dedupe_tuple as dedupe_tuple +from .langhelpers import Dispatcher as Dispatcher +from .langhelpers import EMPTY_DICT as EMPTY_DICT +from .langhelpers import immutabledict as immutabledict +from .langhelpers import memoized_property as memoized_property +from .langhelpers import ModuleClsProxy as ModuleClsProxy +from .langhelpers import not_none as not_none +from .langhelpers import rev_id as rev_id +from .langhelpers import to_list as to_list +from .langhelpers import to_tuple as to_tuple +from .langhelpers import unique_list as unique_list +from .messaging import err as err +from .messaging import format_as_comma as format_as_comma +from .messaging import msg as msg +from .messaging import obfuscate_url_pw as obfuscate_url_pw +from .messaging import status as status +from .messaging import warn as warn +from .messaging import write_outstream as write_outstream +from .pyfiles import coerce_resource_to_filename as coerce_resource_to_filename +from .pyfiles import load_python_file as load_python_file +from .pyfiles import pyc_file_from_path as pyc_file_from_path +from .pyfiles import template_to_file as template_to_file +from .sqla_compat import has_computed as has_computed +from .sqla_compat import sqla_13 as sqla_13 +from .sqla_compat import sqla_14 as sqla_14 +from .sqla_compat import sqla_2 as sqla_2 + + +if not sqla_13: + raise CommandError("SQLAlchemy 1.3.0 or greater is required.") diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/compat.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..e185cc417204295070406b9a77231c48b3d6c38e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/compat.py @@ -0,0 +1,89 @@ +# mypy: no-warn-unused-ignores + +from __future__ import annotations + +from configparser import ConfigParser +import io +import os +import sys +import typing +from typing import Any +from typing import List +from typing import Optional +from typing import Sequence +from typing import Union + +if True: + # zimports hack for too-long names + from sqlalchemy.util import ( # noqa: F401 + inspect_getfullargspec as inspect_getfullargspec, + ) + from sqlalchemy.util.compat import ( # noqa: F401 + inspect_formatargspec as inspect_formatargspec, + ) + +is_posix = os.name == "posix" + +py311 = sys.version_info >= (3, 11) +py310 = sys.version_info >= (3, 10) +py39 = sys.version_info >= (3, 9) + + +# produce a wrapper that allows encoded text to stream +# into a given buffer, but doesn't close it. +# not sure of a more idiomatic approach to this. +class EncodedIO(io.TextIOWrapper): + def close(self) -> None: + pass + + +if py39: + from importlib import resources as _resources + + importlib_resources = _resources + from importlib import metadata as _metadata + + importlib_metadata = _metadata + from importlib.metadata import EntryPoint as EntryPoint +else: + import importlib_resources # type:ignore # noqa + import importlib_metadata # type:ignore # noqa + from importlib_metadata import EntryPoint # type:ignore # noqa + + +def importlib_metadata_get(group: str) -> Sequence[EntryPoint]: + ep = importlib_metadata.entry_points() + if hasattr(ep, "select"): + return ep.select(group=group) + else: + return ep.get(group, ()) # type: ignore + + +def formatannotation_fwdref( + annotation: Any, base_module: Optional[Any] = None +) -> str: + """vendored from python 3.7""" + # copied over _formatannotation from sqlalchemy 2.0 + + if isinstance(annotation, str): + return annotation + + if getattr(annotation, "__module__", None) == "typing": + return repr(annotation).replace("typing.", "").replace("~", "") + if isinstance(annotation, type): + if annotation.__module__ in ("builtins", base_module): + return repr(annotation.__qualname__) + return annotation.__module__ + "." + annotation.__qualname__ + elif isinstance(annotation, typing.TypeVar): + return repr(annotation).replace("~", "") + return repr(annotation).replace("~", "") + + +def read_config_parser( + file_config: ConfigParser, + file_argument: Sequence[Union[str, os.PathLike[str]]], +) -> List[str]: + if py310: + return file_config.read(file_argument, encoding="locale") + else: + return file_config.read(file_argument) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/editor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/editor.py new file mode 100644 index 0000000000000000000000000000000000000000..f1d1557f74c8977efa0b22535f45f44a2c9e2564 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/editor.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import os +from os.path import exists +from os.path import join +from os.path import splitext +from subprocess import check_call +from typing import Dict +from typing import List +from typing import Mapping +from typing import Optional + +from .compat import is_posix +from .exc import CommandError + + +def open_in_editor( + filename: str, environ: Optional[Dict[str, str]] = None +) -> None: + """ + Opens the given file in a text editor. If the environment variable + ``EDITOR`` is set, this is taken as preference. + + Otherwise, a list of commonly installed editors is tried. + + If no editor matches, an :py:exc:`OSError` is raised. + + :param filename: The filename to open. Will be passed verbatim to the + editor command. + :param environ: An optional drop-in replacement for ``os.environ``. Used + mainly for testing. + """ + env = os.environ if environ is None else environ + try: + editor = _find_editor(env) + check_call([editor, filename]) + except Exception as exc: + raise CommandError("Error executing editor (%s)" % (exc,)) from exc + + +def _find_editor(environ: Mapping[str, str]) -> str: + candidates = _default_editors() + for i, var in enumerate(("EDITOR", "VISUAL")): + if var in environ: + user_choice = environ[var] + if exists(user_choice): + return user_choice + if os.sep not in user_choice: + candidates.insert(i, user_choice) + + for candidate in candidates: + path = _find_executable(candidate, environ) + if path is not None: + return path + raise OSError( + "No suitable editor found. Please set the " + '"EDITOR" or "VISUAL" environment variables' + ) + + +def _find_executable( + candidate: str, environ: Mapping[str, str] +) -> Optional[str]: + # Assuming this is on the PATH, we need to determine it's absolute + # location. Otherwise, ``check_call`` will fail + if not is_posix and splitext(candidate)[1] != ".exe": + candidate += ".exe" + for path in environ.get("PATH", "").split(os.pathsep): + value = join(path, candidate) + if exists(value): + return value + return None + + +def _default_editors() -> List[str]: + # Look for an editor. Prefer the user's choice by env-var, fall back to + # most commonly installed editor (nano/vim) + if is_posix: + return ["sensible-editor", "editor", "nano", "vim", "code"] + else: + return ["code.exe", "notepad++.exe", "notepad.exe"] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/exc.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/exc.py new file mode 100644 index 0000000000000000000000000000000000000000..0d0496b1e2967c5bdaca854531a9a2df339e425f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/exc.py @@ -0,0 +1,6 @@ +class CommandError(Exception): + pass + + +class AutogenerateDiffsDetected(CommandError): + pass diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/langhelpers.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/langhelpers.py new file mode 100644 index 0000000000000000000000000000000000000000..4a5bf09a98bba393e5d61a8abf67ba011ab52b71 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/langhelpers.py @@ -0,0 +1,335 @@ +from __future__ import annotations + +import collections +from collections.abc import Iterable +import textwrap +from typing import Any +from typing import Callable +from typing import cast +from typing import Dict +from typing import List +from typing import Mapping +from typing import MutableMapping +from typing import NoReturn +from typing import Optional +from typing import overload +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union +import uuid +import warnings + +from sqlalchemy.util import asbool as asbool # noqa: F401 +from sqlalchemy.util import immutabledict as immutabledict # noqa: F401 +from sqlalchemy.util import to_list as to_list # noqa: F401 +from sqlalchemy.util import unique_list as unique_list + +from .compat import inspect_getfullargspec + +if True: + # zimports workaround :( + from sqlalchemy.util import ( # noqa: F401 + memoized_property as memoized_property, + ) + + +EMPTY_DICT: Mapping[Any, Any] = immutabledict() +_T = TypeVar("_T", bound=Any) + +_C = TypeVar("_C", bound=Callable[..., Any]) + + +class _ModuleClsMeta(type): + def __setattr__(cls, key: str, value: Callable[..., Any]) -> None: + super().__setattr__(key, value) + cls._update_module_proxies(key) # type: ignore + + +class ModuleClsProxy(metaclass=_ModuleClsMeta): + """Create module level proxy functions for the + methods on a given class. + + The functions will have a compatible signature + as the methods. + + """ + + _setups: Dict[ + Type[Any], + Tuple[ + Set[str], + List[Tuple[MutableMapping[str, Any], MutableMapping[str, Any]]], + ], + ] = collections.defaultdict(lambda: (set(), [])) + + @classmethod + def _update_module_proxies(cls, name: str) -> None: + attr_names, modules = cls._setups[cls] + for globals_, locals_ in modules: + cls._add_proxied_attribute(name, globals_, locals_, attr_names) + + def _install_proxy(self) -> None: + attr_names, modules = self._setups[self.__class__] + for globals_, locals_ in modules: + globals_["_proxy"] = self + for attr_name in attr_names: + globals_[attr_name] = getattr(self, attr_name) + + def _remove_proxy(self) -> None: + attr_names, modules = self._setups[self.__class__] + for globals_, locals_ in modules: + globals_["_proxy"] = None + for attr_name in attr_names: + del globals_[attr_name] + + @classmethod + def create_module_class_proxy( + cls, + globals_: MutableMapping[str, Any], + locals_: MutableMapping[str, Any], + ) -> None: + attr_names, modules = cls._setups[cls] + modules.append((globals_, locals_)) + cls._setup_proxy(globals_, locals_, attr_names) + + @classmethod + def _setup_proxy( + cls, + globals_: MutableMapping[str, Any], + locals_: MutableMapping[str, Any], + attr_names: Set[str], + ) -> None: + for methname in dir(cls): + cls._add_proxied_attribute(methname, globals_, locals_, attr_names) + + @classmethod + def _add_proxied_attribute( + cls, + methname: str, + globals_: MutableMapping[str, Any], + locals_: MutableMapping[str, Any], + attr_names: Set[str], + ) -> None: + if not methname.startswith("_"): + meth = getattr(cls, methname) + if callable(meth): + locals_[methname] = cls._create_method_proxy( + methname, globals_, locals_ + ) + else: + attr_names.add(methname) + + @classmethod + def _create_method_proxy( + cls, + name: str, + globals_: MutableMapping[str, Any], + locals_: MutableMapping[str, Any], + ) -> Callable[..., Any]: + fn = getattr(cls, name) + + def _name_error(name: str, from_: Exception) -> NoReturn: + raise NameError( + "Can't invoke function '%s', as the proxy object has " + "not yet been " + "established for the Alembic '%s' class. " + "Try placing this code inside a callable." + % (name, cls.__name__) + ) from from_ + + globals_["_name_error"] = _name_error + + translations = getattr(fn, "_legacy_translations", []) + if translations: + spec = inspect_getfullargspec(fn) + if spec[0] and spec[0][0] == "self": + spec[0].pop(0) + + outer_args = inner_args = "*args, **kw" + translate_str = "args, kw = _translate(%r, %r, %r, args, kw)" % ( + fn.__name__, + tuple(spec), + translations, + ) + + def translate( + fn_name: str, spec: Any, translations: Any, args: Any, kw: Any + ) -> Any: + return_kw = {} + return_args = [] + + for oldname, newname in translations: + if oldname in kw: + warnings.warn( + "Argument %r is now named %r " + "for method %s()." % (oldname, newname, fn_name) + ) + return_kw[newname] = kw.pop(oldname) + return_kw.update(kw) + + args = list(args) + if spec[3]: + pos_only = spec[0][: -len(spec[3])] + else: + pos_only = spec[0] + for arg in pos_only: + if arg not in return_kw: + try: + return_args.append(args.pop(0)) + except IndexError: + raise TypeError( + "missing required positional argument: %s" + % arg + ) + return_args.extend(args) + + return return_args, return_kw + + globals_["_translate"] = translate + else: + outer_args = "*args, **kw" + inner_args = "*args, **kw" + translate_str = "" + + func_text = textwrap.dedent( + """\ + def %(name)s(%(args)s): + %(doc)r + %(translate)s + try: + p = _proxy + except NameError as ne: + _name_error('%(name)s', ne) + return _proxy.%(name)s(%(apply_kw)s) + e + """ + % { + "name": name, + "translate": translate_str, + "args": outer_args, + "apply_kw": inner_args, + "doc": fn.__doc__, + } + ) + lcl: MutableMapping[str, Any] = {} + + exec(func_text, cast("Dict[str, Any]", globals_), lcl) + return cast("Callable[..., Any]", lcl[name]) + + +def _with_legacy_names(translations: Any) -> Any: + def decorate(fn: _C) -> _C: + fn._legacy_translations = translations # type: ignore[attr-defined] + return fn + + return decorate + + +def rev_id() -> str: + return uuid.uuid4().hex[-12:] + + +@overload +def to_tuple(x: Any, default: Tuple[Any, ...]) -> Tuple[Any, ...]: + ... + + +@overload +def to_tuple(x: None, default: Optional[_T] = ...) -> _T: + ... + + +@overload +def to_tuple( + x: Any, default: Optional[Tuple[Any, ...]] = None +) -> Tuple[Any, ...]: + ... + + +def to_tuple( + x: Any, default: Optional[Tuple[Any, ...]] = None +) -> Optional[Tuple[Any, ...]]: + if x is None: + return default + elif isinstance(x, str): + return (x,) + elif isinstance(x, Iterable): + return tuple(x) + else: + return (x,) + + +def dedupe_tuple(tup: Tuple[str, ...]) -> Tuple[str, ...]: + return tuple(unique_list(tup)) + + +class Dispatcher: + def __init__(self, uselist: bool = False) -> None: + self._registry: Dict[Tuple[Any, ...], Any] = {} + self.uselist = uselist + + def dispatch_for( + self, target: Any, qualifier: str = "default" + ) -> Callable[[_C], _C]: + def decorate(fn: _C) -> _C: + if self.uselist: + self._registry.setdefault((target, qualifier), []).append(fn) + else: + assert (target, qualifier) not in self._registry + self._registry[(target, qualifier)] = fn + return fn + + return decorate + + def dispatch(self, obj: Any, qualifier: str = "default") -> Any: + if isinstance(obj, str): + targets: Sequence[Any] = [obj] + elif isinstance(obj, type): + targets = obj.__mro__ + else: + targets = type(obj).__mro__ + + for spcls in targets: + if qualifier != "default" and (spcls, qualifier) in self._registry: + return self._fn_or_list(self._registry[(spcls, qualifier)]) + elif (spcls, "default") in self._registry: + return self._fn_or_list(self._registry[(spcls, "default")]) + else: + raise ValueError("no dispatch function for object: %s" % obj) + + def _fn_or_list( + self, fn_or_list: Union[List[Callable[..., Any]], Callable[..., Any]] + ) -> Callable[..., Any]: + if self.uselist: + + def go(*arg: Any, **kw: Any) -> None: + if TYPE_CHECKING: + assert isinstance(fn_or_list, Sequence) + for fn in fn_or_list: + fn(*arg, **kw) + + return go + else: + return fn_or_list # type: ignore + + def branch(self) -> Dispatcher: + """Return a copy of this dispatcher that is independently + writable.""" + + d = Dispatcher() + if self.uselist: + d._registry.update( + (k, [fn for fn in self._registry[k]]) for k in self._registry + ) + else: + d._registry.update(self._registry) + return d + + +def not_none(value: Optional[_T]) -> _T: + assert value is not None + return value diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/messaging.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/messaging.py new file mode 100644 index 0000000000000000000000000000000000000000..5f14d597554e281ee098afbbb0f2864cec0fd2e8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/messaging.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +from collections.abc import Iterable +from contextlib import contextmanager +import logging +import sys +import textwrap +from typing import Iterator +from typing import Optional +from typing import TextIO +from typing import Union +import warnings + +from sqlalchemy.engine import url + +from . import sqla_compat + +log = logging.getLogger(__name__) + +# disable "no handler found" errors +logging.getLogger("alembic").addHandler(logging.NullHandler()) + + +try: + import fcntl + import termios + import struct + + ioctl = fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack("HHHH", 0, 0, 0, 0)) + _h, TERMWIDTH, _hp, _wp = struct.unpack("HHHH", ioctl) + if TERMWIDTH <= 0: # can occur if running in emacs pseudo-tty + TERMWIDTH = None +except (ImportError, OSError): + TERMWIDTH = None + + +def write_outstream( + stream: TextIO, *text: Union[str, bytes], quiet: bool = False +) -> None: + if quiet: + return + encoding = getattr(stream, "encoding", "ascii") or "ascii" + for t in text: + if not isinstance(t, bytes): + t = t.encode(encoding, "replace") + t = t.decode(encoding) + try: + stream.write(t) + except OSError: + # suppress "broken pipe" errors. + # no known way to handle this on Python 3 however + # as the exception is "ignored" (noisily) in TextIOWrapper. + break + + +@contextmanager +def status( + status_msg: str, newline: bool = False, quiet: bool = False +) -> Iterator[None]: + msg(status_msg + " ...", newline, flush=True, quiet=quiet) + try: + yield + except: + if not quiet: + write_outstream(sys.stdout, " FAILED\n") + raise + else: + if not quiet: + write_outstream(sys.stdout, " done\n") + + +def err(message: str, quiet: bool = False) -> None: + log.error(message) + msg(f"FAILED: {message}", quiet=quiet) + sys.exit(-1) + + +def obfuscate_url_pw(input_url: str) -> str: + u = url.make_url(input_url) + return sqla_compat.url_render_as_string(u, hide_password=True) # type: ignore # noqa: E501 + + +def warn(msg: str, stacklevel: int = 2) -> None: + warnings.warn(msg, UserWarning, stacklevel=stacklevel) + + +def msg( + msg: str, newline: bool = True, flush: bool = False, quiet: bool = False +) -> None: + if quiet: + return + if TERMWIDTH is None: + write_outstream(sys.stdout, msg) + if newline: + write_outstream(sys.stdout, "\n") + else: + # left indent output lines + lines = textwrap.wrap(msg, TERMWIDTH) + if len(lines) > 1: + for line in lines[0:-1]: + write_outstream(sys.stdout, " ", line, "\n") + write_outstream(sys.stdout, " ", lines[-1], ("\n" if newline else "")) + if flush: + sys.stdout.flush() + + +def format_as_comma(value: Optional[Union[str, Iterable[str]]]) -> str: + if value is None: + return "" + elif isinstance(value, str): + return value + elif isinstance(value, Iterable): + return ", ".join(value) + else: + raise ValueError("Don't know how to comma-format %r" % value) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/pyfiles.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/pyfiles.py new file mode 100644 index 0000000000000000000000000000000000000000..973bd458e5ce615a2b31aa3eeaeec61d6c2f709e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/pyfiles.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import atexit +from contextlib import ExitStack +import importlib +import importlib.machinery +import importlib.util +import os +import re +import tempfile +from types import ModuleType +from typing import Any +from typing import Optional + +from mako import exceptions +from mako.template import Template + +from . import compat +from .exc import CommandError + + +def template_to_file( + template_file: str, dest: str, output_encoding: str, **kw: Any +) -> None: + template = Template(filename=template_file) + try: + output = template.render_unicode(**kw).encode(output_encoding) + except: + with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as ntf: + ntf.write( + exceptions.text_error_template() + .render_unicode() + .encode(output_encoding) + ) + fname = ntf.name + raise CommandError( + "Template rendering failed; see %s for a " + "template-oriented traceback." % fname + ) + else: + with open(dest, "wb") as f: + f.write(output) + + +def coerce_resource_to_filename(fname: str) -> str: + """Interpret a filename as either a filesystem location or as a package + resource. + + Names that are non absolute paths and contain a colon + are interpreted as resources and coerced to a file location. + + """ + if not os.path.isabs(fname) and ":" in fname: + tokens = fname.split(":") + + # from https://importlib-resources.readthedocs.io/en/latest/migration.html#pkg-resources-resource-filename # noqa E501 + + file_manager = ExitStack() + atexit.register(file_manager.close) + + ref = compat.importlib_resources.files(tokens[0]) + for tok in tokens[1:]: + ref = ref / tok + fname = file_manager.enter_context( # type: ignore[assignment] + compat.importlib_resources.as_file(ref) + ) + return fname + + +def pyc_file_from_path(path: str) -> Optional[str]: + """Given a python source path, locate the .pyc.""" + + candidate = importlib.util.cache_from_source(path) + if os.path.exists(candidate): + return candidate + + # even for pep3147, fall back to the old way of finding .pyc files, + # to support sourceless operation + filepath, ext = os.path.splitext(path) + for ext in importlib.machinery.BYTECODE_SUFFIXES: + if os.path.exists(filepath + ext): + return filepath + ext + else: + return None + + +def load_python_file(dir_: str, filename: str) -> ModuleType: + """Load a file from the given path as a Python module.""" + + module_id = re.sub(r"\W", "_", filename) + path = os.path.join(dir_, filename) + _, ext = os.path.splitext(filename) + if ext == ".py": + if os.path.exists(path): + module = load_module_py(module_id, path) + else: + pyc_path = pyc_file_from_path(path) + if pyc_path is None: + raise ImportError("Can't find Python file %s" % path) + else: + module = load_module_py(module_id, pyc_path) + elif ext in (".pyc", ".pyo"): + module = load_module_py(module_id, path) + else: + assert False + return module + + +def load_module_py(module_id: str, path: str) -> ModuleType: + spec = importlib.util.spec_from_file_location(module_id, path) + assert spec + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) # type: ignore + return module diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/sqla_compat.py b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/sqla_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..8489c19fac7c163dc9053d2f52606855117d60a6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/alembic/util/sqla_compat.py @@ -0,0 +1,665 @@ +# mypy: allow-untyped-defs, allow-incomplete-defs, allow-untyped-calls +# mypy: no-warn-return-any, allow-any-generics + +from __future__ import annotations + +import contextlib +import re +from typing import Any +from typing import Callable +from typing import Dict +from typing import Iterable +from typing import Iterator +from typing import Mapping +from typing import Optional +from typing import Protocol +from typing import Set +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from sqlalchemy import __version__ +from sqlalchemy import inspect +from sqlalchemy import schema +from sqlalchemy import sql +from sqlalchemy import types as sqltypes +from sqlalchemy.engine import url +from sqlalchemy.schema import CheckConstraint +from sqlalchemy.schema import Column +from sqlalchemy.schema import ForeignKeyConstraint +from sqlalchemy.sql import visitors +from sqlalchemy.sql.base import DialectKWArgs +from sqlalchemy.sql.elements import BindParameter +from sqlalchemy.sql.elements import ColumnClause +from sqlalchemy.sql.elements import quoted_name +from sqlalchemy.sql.elements import TextClause +from sqlalchemy.sql.elements import UnaryExpression +from sqlalchemy.sql.visitors import traverse +from typing_extensions import TypeGuard + +if TYPE_CHECKING: + from sqlalchemy import ClauseElement + from sqlalchemy import Index + from sqlalchemy import Table + from sqlalchemy.engine import Connection + from sqlalchemy.engine import Dialect + from sqlalchemy.engine import Transaction + from sqlalchemy.engine.reflection import Inspector + from sqlalchemy.sql.base import ColumnCollection + from sqlalchemy.sql.compiler import SQLCompiler + from sqlalchemy.sql.dml import Insert + from sqlalchemy.sql.elements import ColumnElement + from sqlalchemy.sql.schema import Constraint + from sqlalchemy.sql.schema import SchemaItem + from sqlalchemy.sql.selectable import Select + from sqlalchemy.sql.selectable import TableClause + +_CE = TypeVar("_CE", bound=Union["ColumnElement[Any]", "SchemaItem"]) + + +class _CompilerProtocol(Protocol): + def __call__(self, element: Any, compiler: Any, **kw: Any) -> str: + ... + + +def _safe_int(value: str) -> Union[int, str]: + try: + return int(value) + except: + return value + + +_vers = tuple( + [_safe_int(x) for x in re.findall(r"(\d+|[abc]\d)", __version__)] +) +sqla_13 = _vers >= (1, 3) +sqla_14 = _vers >= (1, 4) +# https://docs.sqlalchemy.org/en/latest/changelog/changelog_14.html#change-0c6e0cc67dfe6fac5164720e57ef307d +sqla_14_18 = _vers >= (1, 4, 18) +sqla_14_26 = _vers >= (1, 4, 26) +sqla_2 = _vers >= (2,) +sqlalchemy_version = __version__ + +try: + from sqlalchemy.sql.naming import _NONE_NAME as _NONE_NAME # type: ignore[attr-defined] # noqa: E501 +except ImportError: + from sqlalchemy.sql.elements import _NONE_NAME as _NONE_NAME # type: ignore # noqa: E501 + + +class _Unsupported: + "Placeholder for unsupported SQLAlchemy classes" + + +if TYPE_CHECKING: + + def compiles( + element: Type[ClauseElement], *dialects: str + ) -> Callable[[_CompilerProtocol], _CompilerProtocol]: + ... + +else: + from sqlalchemy.ext.compiler import compiles + +try: + from sqlalchemy import Computed as Computed +except ImportError: + if not TYPE_CHECKING: + + class Computed(_Unsupported): + pass + + has_computed = False + has_computed_reflection = False +else: + has_computed = True + has_computed_reflection = _vers >= (1, 3, 16) + +try: + from sqlalchemy import Identity as Identity +except ImportError: + if not TYPE_CHECKING: + + class Identity(_Unsupported): + pass + + has_identity = False +else: + identity_has_dialect_kwargs = issubclass(Identity, DialectKWArgs) + + def _get_identity_options_dict( + identity: Union[Identity, schema.Sequence, None], + dialect_kwargs: bool = False, + ) -> Dict[str, Any]: + if identity is None: + return {} + elif identity_has_dialect_kwargs: + as_dict = identity._as_dict() # type: ignore + if dialect_kwargs: + assert isinstance(identity, DialectKWArgs) + as_dict.update(identity.dialect_kwargs) + else: + as_dict = {} + if isinstance(identity, Identity): + # always=None means something different than always=False + as_dict["always"] = identity.always + if identity.on_null is not None: + as_dict["on_null"] = identity.on_null + # attributes common to Identity and Sequence + attrs = ( + "start", + "increment", + "minvalue", + "maxvalue", + "nominvalue", + "nomaxvalue", + "cycle", + "cache", + "order", + ) + as_dict.update( + { + key: getattr(identity, key, None) + for key in attrs + if getattr(identity, key, None) is not None + } + ) + return as_dict + + has_identity = True + +if sqla_2: + from sqlalchemy.sql.base import _NoneName +else: + from sqlalchemy.util import symbol as _NoneName # type: ignore[assignment] + + +_ConstraintName = Union[None, str, _NoneName] + +_ConstraintNameDefined = Union[str, _NoneName] + + +def constraint_name_defined( + name: _ConstraintName, +) -> TypeGuard[_ConstraintNameDefined]: + return name is _NONE_NAME or isinstance(name, (str, _NoneName)) + + +def constraint_name_string( + name: _ConstraintName, +) -> TypeGuard[str]: + return isinstance(name, str) + + +def constraint_name_or_none( + name: _ConstraintName, +) -> Optional[str]: + return name if constraint_name_string(name) else None + + +AUTOINCREMENT_DEFAULT = "auto" + + +@contextlib.contextmanager +def _ensure_scope_for_ddl( + connection: Optional[Connection], +) -> Iterator[None]: + try: + in_transaction = connection.in_transaction # type: ignore[union-attr] + except AttributeError: + # catch for MockConnection, None + in_transaction = None + pass + + # yield outside the catch + if in_transaction is None: + yield + else: + if not in_transaction(): + assert connection is not None + with connection.begin(): + yield + else: + yield + + +def url_render_as_string(url, hide_password=True): + if sqla_14: + return url.render_as_string(hide_password=hide_password) + else: + return url.__to_string__(hide_password=hide_password) + + +def _safe_begin_connection_transaction( + connection: Connection, +) -> Transaction: + transaction = _get_connection_transaction(connection) + if transaction: + return transaction + else: + return connection.begin() + + +def _safe_commit_connection_transaction( + connection: Connection, +) -> None: + transaction = _get_connection_transaction(connection) + if transaction: + transaction.commit() + + +def _safe_rollback_connection_transaction( + connection: Connection, +) -> None: + transaction = _get_connection_transaction(connection) + if transaction: + transaction.rollback() + + +def _get_connection_in_transaction(connection: Optional[Connection]) -> bool: + try: + in_transaction = connection.in_transaction # type: ignore + except AttributeError: + # catch for MockConnection + return False + else: + return in_transaction() + + +def _idx_table_bound_expressions(idx: Index) -> Iterable[ColumnElement[Any]]: + return idx.expressions # type: ignore + + +def _copy(schema_item: _CE, **kw) -> _CE: + if hasattr(schema_item, "_copy"): + return schema_item._copy(**kw) + else: + return schema_item.copy(**kw) # type: ignore[union-attr] + + +def _get_connection_transaction( + connection: Connection, +) -> Optional[Transaction]: + if sqla_14: + return connection.get_transaction() + else: + r = connection._root # type: ignore[attr-defined] + return r._Connection__transaction + + +def _create_url(*arg, **kw) -> url.URL: + if hasattr(url.URL, "create"): + return url.URL.create(*arg, **kw) + else: + return url.URL(*arg, **kw) + + +def _connectable_has_table( + connectable: Connection, tablename: str, schemaname: Union[str, None] +) -> bool: + if sqla_14: + return inspect(connectable).has_table(tablename, schemaname) + else: + return connectable.dialect.has_table( + connectable, tablename, schemaname + ) + + +def _exec_on_inspector(inspector, statement, **params): + if sqla_14: + with inspector._operation_context() as conn: + return conn.execute(statement, params) + else: + return inspector.bind.execute(statement, params) + + +def _nullability_might_be_unset(metadata_column): + if not sqla_14: + return metadata_column.nullable + else: + from sqlalchemy.sql import schema + + return ( + metadata_column._user_defined_nullable is schema.NULL_UNSPECIFIED + ) + + +def _server_default_is_computed(*server_default) -> bool: + if not has_computed: + return False + else: + return any(isinstance(sd, Computed) for sd in server_default) + + +def _server_default_is_identity(*server_default) -> bool: + if not sqla_14: + return False + else: + return any(isinstance(sd, Identity) for sd in server_default) + + +def _table_for_constraint(constraint: Constraint) -> Table: + if isinstance(constraint, ForeignKeyConstraint): + table = constraint.parent + assert table is not None + return table # type: ignore[return-value] + else: + return constraint.table + + +def _columns_for_constraint(constraint): + if isinstance(constraint, ForeignKeyConstraint): + return [fk.parent for fk in constraint.elements] + elif isinstance(constraint, CheckConstraint): + return _find_columns(constraint.sqltext) + else: + return list(constraint.columns) + + +def _reflect_table(inspector: Inspector, table: Table) -> None: + if sqla_14: + return inspector.reflect_table(table, None) + else: + return inspector.reflecttable( # type: ignore[attr-defined] + table, None + ) + + +def _resolve_for_variant(type_, dialect): + if _type_has_variants(type_): + base_type, mapping = _get_variant_mapping(type_) + return mapping.get(dialect.name, base_type) + else: + return type_ + + +if hasattr(sqltypes.TypeEngine, "_variant_mapping"): + + def _type_has_variants(type_): + return bool(type_._variant_mapping) + + def _get_variant_mapping(type_): + return type_, type_._variant_mapping + +else: + + def _type_has_variants(type_): + return type(type_) is sqltypes.Variant + + def _get_variant_mapping(type_): + return type_.impl, type_.mapping + + +def _fk_spec(constraint: ForeignKeyConstraint) -> Any: + if TYPE_CHECKING: + assert constraint.columns is not None + assert constraint.elements is not None + assert isinstance(constraint.parent, Table) + + source_columns = [ + constraint.columns[key].name for key in constraint.column_keys + ] + + source_table = constraint.parent.name + source_schema = constraint.parent.schema + target_schema = constraint.elements[0].column.table.schema + target_table = constraint.elements[0].column.table.name + target_columns = [element.column.name for element in constraint.elements] + ondelete = constraint.ondelete + onupdate = constraint.onupdate + deferrable = constraint.deferrable + initially = constraint.initially + return ( + source_schema, + source_table, + source_columns, + target_schema, + target_table, + target_columns, + onupdate, + ondelete, + deferrable, + initially, + ) + + +def _fk_is_self_referential(constraint: ForeignKeyConstraint) -> bool: + spec = constraint.elements[0]._get_colspec() + tokens = spec.split(".") + tokens.pop(-1) # colname + tablekey = ".".join(tokens) + assert constraint.parent is not None + return tablekey == constraint.parent.key + + +def _is_type_bound(constraint: Constraint) -> bool: + # this deals with SQLAlchemy #3260, don't copy CHECK constraints + # that will be generated by the type. + # new feature added for #3260 + return constraint._type_bound + + +def _find_columns(clause): + """locate Column objects within the given expression.""" + + cols: Set[ColumnElement[Any]] = set() + traverse(clause, {}, {"column": cols.add}) + return cols + + +def _remove_column_from_collection( + collection: ColumnCollection, column: Union[Column[Any], ColumnClause[Any]] +) -> None: + """remove a column from a ColumnCollection.""" + + # workaround for older SQLAlchemy, remove the + # same object that's present + assert column.key is not None + to_remove = collection[column.key] + + # SQLAlchemy 2.0 will use more ReadOnlyColumnCollection + # (renamed from ImmutableColumnCollection) + if hasattr(collection, "_immutable") or hasattr(collection, "_readonly"): + collection._parent.remove(to_remove) + else: + collection.remove(to_remove) + + +def _textual_index_column( + table: Table, text_: Union[str, TextClause, ColumnElement[Any]] +) -> Union[ColumnElement[Any], Column[Any]]: + """a workaround for the Index construct's severe lack of flexibility""" + if isinstance(text_, str): + c = Column(text_, sqltypes.NULLTYPE) + table.append_column(c) + return c + elif isinstance(text_, TextClause): + return _textual_index_element(table, text_) + elif isinstance(text_, _textual_index_element): + return _textual_index_column(table, text_.text) + elif isinstance(text_, sql.ColumnElement): + return _copy_expression(text_, table) + else: + raise ValueError("String or text() construct expected") + + +def _copy_expression(expression: _CE, target_table: Table) -> _CE: + def replace(col): + if ( + isinstance(col, Column) + and col.table is not None + and col.table is not target_table + ): + if col.name in target_table.c: + return target_table.c[col.name] + else: + c = _copy(col) + target_table.append_column(c) + return c + else: + return None + + return visitors.replacement_traverse( # type: ignore[call-overload] + expression, {}, replace + ) + + +class _textual_index_element(sql.ColumnElement): + """Wrap around a sqlalchemy text() construct in such a way that + we appear like a column-oriented SQL expression to an Index + construct. + + The issue here is that currently the Postgresql dialect, the biggest + recipient of functional indexes, keys all the index expressions to + the corresponding column expressions when rendering CREATE INDEX, + so the Index we create here needs to have a .columns collection that + is the same length as the .expressions collection. Ultimately + SQLAlchemy should support text() expressions in indexes. + + See SQLAlchemy issue 3174. + + """ + + __visit_name__ = "_textual_idx_element" + + def __init__(self, table: Table, text: TextClause) -> None: + self.table = table + self.text = text + self.key = text.text + self.fake_column = schema.Column(self.text.text, sqltypes.NULLTYPE) + table.append_column(self.fake_column) + + def get_children(self): + return [self.fake_column] + + +@compiles(_textual_index_element) +def _render_textual_index_column( + element: _textual_index_element, compiler: SQLCompiler, **kw +) -> str: + return compiler.process(element.text, **kw) + + +class _literal_bindparam(BindParameter): + pass + + +@compiles(_literal_bindparam) +def _render_literal_bindparam( + element: _literal_bindparam, compiler: SQLCompiler, **kw +) -> str: + return compiler.render_literal_bindparam(element, **kw) + + +def _column_kwargs(col: Column) -> Mapping: + if sqla_13: + return col.kwargs + else: + return {} + + +def _get_constraint_final_name( + constraint: Union[Index, Constraint], dialect: Optional[Dialect] +) -> Optional[str]: + if constraint.name is None: + return None + assert dialect is not None + if sqla_14: + # for SQLAlchemy 1.4 we would like to have the option to expand + # the use of "deferred" names for constraints as well as to have + # some flexibility with "None" name and similar; make use of new + # SQLAlchemy API to return what would be the final compiled form of + # the name for this dialect. + return dialect.identifier_preparer.format_constraint( + constraint, _alembic_quote=False + ) + else: + # prior to SQLAlchemy 1.4, work around quoting logic to get at the + # final compiled name without quotes. + if hasattr(constraint.name, "quote"): + # might be quoted_name, might be truncated_name, keep it the + # same + quoted_name_cls: type = type(constraint.name) + else: + quoted_name_cls = quoted_name + + new_name = quoted_name_cls(str(constraint.name), quote=False) + constraint = constraint.__class__(name=new_name) + + if isinstance(constraint, schema.Index): + # name should not be quoted. + d = dialect.ddl_compiler(dialect, None) # type: ignore[arg-type] + return d._prepared_index_name(constraint) + else: + # name should not be quoted. + return dialect.identifier_preparer.format_constraint(constraint) + + +def _constraint_is_named( + constraint: Union[Constraint, Index], dialect: Optional[Dialect] +) -> bool: + if sqla_14: + if constraint.name is None: + return False + assert dialect is not None + name = dialect.identifier_preparer.format_constraint( + constraint, _alembic_quote=False + ) + return name is not None + else: + return constraint.name is not None + + +def _is_mariadb(mysql_dialect: Dialect) -> bool: + if sqla_14: + return mysql_dialect.is_mariadb # type: ignore[attr-defined] + else: + return bool( + mysql_dialect.server_version_info + and mysql_dialect._is_mariadb # type: ignore[attr-defined] + ) + + +def _mariadb_normalized_version_info(mysql_dialect): + return mysql_dialect._mariadb_normalized_version_info + + +def _insert_inline(table: Union[TableClause, Table]) -> Insert: + if sqla_14: + return table.insert().inline() + else: + return table.insert(inline=True) # type: ignore[call-arg] + + +if sqla_14: + from sqlalchemy import create_mock_engine + + # weird mypy workaround + from sqlalchemy import select as _sa_select + + _select = _sa_select +else: + from sqlalchemy import create_engine + + def create_mock_engine(url, executor, **kw): # type: ignore[misc] + return create_engine( + "postgresql://", strategy="mock", executor=executor + ) + + def _select(*columns, **kw) -> Select: + return sql.select(list(columns), **kw) # type: ignore[call-overload] + + +def is_expression_index(index: Index) -> bool: + for expr in index.expressions: + if is_expression(expr): + return True + return False + + +def is_expression(expr: Any) -> bool: + while isinstance(expr, UnaryExpression): + expr = expr.element + if not isinstance(expr, ColumnClause) or expr.is_literal: + return True + return False diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/encoding.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..f450ca479e2807ae8ce8ad5eefbf8ec017e41470 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/encoding.py @@ -0,0 +1,66 @@ +import json +import base64 +import struct + + +def to_bytes(x, charset='utf-8', errors='strict'): + if x is None: + return None + if isinstance(x, bytes): + return x + if isinstance(x, str): + return x.encode(charset, errors) + if isinstance(x, (int, float)): + return str(x).encode(charset, errors) + return bytes(x) + + +def to_unicode(x, charset='utf-8', errors='strict'): + if x is None or isinstance(x, str): + return x + if isinstance(x, bytes): + return x.decode(charset, errors) + return str(x) + + +def to_native(x, encoding='ascii'): + if isinstance(x, str): + return x + return x.decode(encoding) + + +def json_loads(s): + return json.loads(s) + + +def json_dumps(data, ensure_ascii=False): + return json.dumps(data, ensure_ascii=ensure_ascii, separators=(',', ':')) + + +def urlsafe_b64decode(s): + s += b'=' * (-len(s) % 4) + return base64.urlsafe_b64decode(s) + + +def urlsafe_b64encode(s): + return base64.urlsafe_b64encode(s).rstrip(b'=') + + +def base64_to_int(s): + data = urlsafe_b64decode(to_bytes(s, charset='ascii')) + buf = struct.unpack('%sB' % len(data), data) + return int(''.join(["%02x" % byte for byte in buf]), 16) + + +def int_to_base64(num): + if num < 0: + raise ValueError('Must be a positive integer') + + s = num.to_bytes((num.bit_length() + 7) // 8, 'big', signed=False) + return to_unicode(urlsafe_b64encode(s)) + + +def json_b64encode(text): + if isinstance(text, dict): + text = json_dumps(text) + return urlsafe_b64encode(to_bytes(text)) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/errors.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..56515baba70eaa075eb64879abe47af946eec422 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/errors.py @@ -0,0 +1,63 @@ +from authlib.consts import default_json_headers + + +class AuthlibBaseError(Exception): + """Base Exception for all errors in Authlib.""" + + #: short-string error code + error = None + #: long-string to describe this error + description = '' + #: web page that describes this error + uri = None + + def __init__(self, error=None, description=None, uri=None): + if error is not None: + self.error = error + if description is not None: + self.description = description + if uri is not None: + self.uri = uri + + message = f'{self.error}: {self.description}' + super().__init__(message) + + def __repr__(self): + return f'<{self.__class__.__name__} "{self.error}">' + + +class AuthlibHTTPError(AuthlibBaseError): + #: HTTP status code + status_code = 400 + + def __init__(self, error=None, description=None, uri=None, + status_code=None): + super().__init__(error, description, uri) + if status_code is not None: + self.status_code = status_code + + def get_error_description(self): + return self.description + + def get_body(self): + error = [('error', self.error)] + + if self.description: + error.append(('error_description', self.description)) + + if self.uri: + error.append(('error_uri', self.uri)) + return error + + def get_headers(self): + return default_json_headers[:] + + def __call__(self, uri=None): + self.uri = uri + body = dict(self.get_body()) + headers = self.get_headers() + return self.status_code, body, headers + + +class ContinueIteration(AuthlibBaseError): + pass diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/security.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/security.py new file mode 100644 index 0000000000000000000000000000000000000000..b05ea1443064b40163a878f4bca64a2c721ce4c1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/security.py @@ -0,0 +1,19 @@ +import os +import string +import random + +UNICODE_ASCII_CHARACTER_SET = string.ascii_letters + string.digits + + +def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET): + rand = random.SystemRandom() + return ''.join(rand.choice(chars) for _ in range(length)) + + +def is_secure_transport(uri): + """Check if the uri is over ssl.""" + if os.getenv('AUTHLIB_INSECURE_TRANSPORT'): + return True + + uri = uri.lower() + return uri.startswith(('https://', 'http://localhost:')) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/urls.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..1d1847fa3e56d6631ef6c1a218e11b1110d94e2e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/common/urls.py @@ -0,0 +1,146 @@ +""" + authlib.util.urls + ~~~~~~~~~~~~~~~~~ + + Wrapper functions for URL encoding and decoding. +""" + +import re +from urllib.parse import quote as _quote +from urllib.parse import unquote as _unquote +from urllib.parse import urlencode as _urlencode +import urllib.parse as urlparse + +from .encoding import to_unicode, to_bytes + +always_safe = ( + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789_.-' +) +urlencoded = set(always_safe) | set('=&;:%+~,*@!()/?') +INVALID_HEX_PATTERN = re.compile(r'%[^0-9A-Fa-f]|%[0-9A-Fa-f][^0-9A-Fa-f]') + + +def url_encode(params): + encoded = [] + for k, v in params: + encoded.append((to_bytes(k), to_bytes(v))) + return to_unicode(_urlencode(encoded)) + + +def url_decode(query): + """Decode a query string in x-www-form-urlencoded format into a sequence + of two-element tuples. + + Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce + correct formatting of the query string by validation. If validation fails + a ValueError will be raised. urllib.parse_qsl will only raise errors if + any of name-value pairs omits the equals sign. + """ + # Check if query contains invalid characters + if query and not set(query) <= urlencoded: + error = ("Error trying to decode a non urlencoded string. " + "Found invalid characters: %s " + "in the string: '%s'. " + "Please ensure the request/response body is " + "x-www-form-urlencoded.") + raise ValueError(error % (set(query) - urlencoded, query)) + + # Check for correctly hex encoded values using a regular expression + # All encoded values begin with % followed by two hex characters + # correct = %00, %A0, %0A, %FF + # invalid = %G0, %5H, %PO + if INVALID_HEX_PATTERN.search(query): + raise ValueError('Invalid hex encoding in query string.') + + # We encode to utf-8 prior to parsing because parse_qsl behaves + # differently on unicode input in python 2 and 3. + # Python 2.7 + # >>> urlparse.parse_qsl(u'%E5%95%A6%E5%95%A6') + # u'\xe5\x95\xa6\xe5\x95\xa6' + # Python 2.7, non unicode input gives the same + # >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6') + # '\xe5\x95\xa6\xe5\x95\xa6' + # but now we can decode it to unicode + # >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6').decode('utf-8') + # u'\u5566\u5566' + # Python 3.3 however + # >>> urllib.parse.parse_qsl(u'%E5%95%A6%E5%95%A6') + # u'\u5566\u5566' + + # We want to allow queries such as "c2" whereas urlparse.parse_qsl + # with the strict_parsing flag will not. + params = urlparse.parse_qsl(query, keep_blank_values=True) + + # unicode all the things + decoded = [] + for k, v in params: + decoded.append((to_unicode(k), to_unicode(v))) + return decoded + + +def add_params_to_qs(query, params): + """Extend a query with a list of two-tuples.""" + if isinstance(params, dict): + params = params.items() + + qs = urlparse.parse_qsl(query, keep_blank_values=True) + qs.extend(params) + return url_encode(qs) + + +def add_params_to_uri(uri, params, fragment=False): + """Add a list of two-tuples to the uri query components.""" + sch, net, path, par, query, fra = urlparse.urlparse(uri) + if fragment: + fra = add_params_to_qs(fra, params) + else: + query = add_params_to_qs(query, params) + return urlparse.urlunparse((sch, net, path, par, query, fra)) + + +def quote(s, safe=b'/'): + return to_unicode(_quote(to_bytes(s), safe)) + + +def unquote(s): + return to_unicode(_unquote(s)) + + +def quote_url(s): + return quote(s, b'~@#$&()*!+=:;,.?/\'') + + +def extract_params(raw): + """Extract parameters and return them as a list of 2-tuples. + + Will successfully extract parameters from urlencoded query strings, + dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an + empty list of parameters. Any other input will result in a return + value of None. + """ + if isinstance(raw, (list, tuple)): + try: + raw = dict(raw) + except (TypeError, ValueError): + return None + + if isinstance(raw, dict): + params = [] + for k, v in raw.items(): + params.append((to_unicode(k), to_unicode(v))) + return params + + if not raw: + return None + + try: + return url_decode(raw) + except ValueError: + return None + + +def is_valid_url(url): + parsed = urlparse.urlparse(url) + return parsed.scheme and parsed.hostname diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..077301f21c07adaaea1d1aff23d9838f2a4300e4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/__init__.py @@ -0,0 +1,18 @@ +from .registry import BaseOAuth +from .sync_app import BaseApp, OAuth1Mixin, OAuth2Mixin +from .sync_openid import OpenIDMixin +from .framework_integration import FrameworkIntegration +from .errors import ( + OAuthError, MissingRequestTokenError, MissingTokenError, + TokenExpiredError, InvalidTokenError, UnsupportedTokenTypeError, + MismatchingStateError, +) + +__all__ = [ + 'BaseOAuth', + 'BaseApp', 'OAuth1Mixin', 'OAuth2Mixin', + 'OpenIDMixin', 'FrameworkIntegration', + 'OAuthError', 'MissingRequestTokenError', 'MissingTokenError', + 'TokenExpiredError', 'InvalidTokenError', 'UnsupportedTokenTypeError', + 'MismatchingStateError', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/async_app.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/async_app.py new file mode 100644 index 0000000000000000000000000000000000000000..640896e7dc5b7bfa85507ca626eee644d3aa25ac --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/async_app.py @@ -0,0 +1,144 @@ +import time +import logging +from authlib.common.urls import urlparse +from .errors import ( + MissingRequestTokenError, + MissingTokenError, +) +from .sync_app import OAuth1Base, OAuth2Base + +log = logging.getLogger(__name__) + +__all__ = ['AsyncOAuth1Mixin', 'AsyncOAuth2Mixin'] + + +class AsyncOAuth1Mixin(OAuth1Base): + async def request(self, method, url, token=None, **kwargs): + async with self._get_oauth_client() as session: + return await _http_request(self, session, method, url, token, kwargs) + + async def create_authorization_url(self, redirect_uri=None, **kwargs): + """Generate the authorization url and state for HTTP redirect. + + :param redirect_uri: Callback or redirect URI for authorization. + :param kwargs: Extra parameters to include. + :return: dict + """ + if not self.authorize_url: + raise RuntimeError('Missing "authorize_url" value') + + if self.authorize_params: + kwargs.update(self.authorize_params) + + async with self._get_oauth_client() as client: + client.redirect_uri = redirect_uri + params = {} + if self.request_token_params: + params.update(self.request_token_params) + request_token = await client.fetch_request_token(self.request_token_url, **params) + log.debug(f'Fetch request token: {request_token!r}') + url = client.create_authorization_url(self.authorize_url, **kwargs) + state = request_token['oauth_token'] + return {'url': url, 'request_token': request_token, 'state': state} + + async def fetch_access_token(self, request_token=None, **kwargs): + """Fetch access token in one step. + + :param request_token: A previous request token for OAuth 1. + :param kwargs: Extra parameters to fetch access token. + :return: A token dict. + """ + async with self._get_oauth_client() as client: + if request_token is None: + raise MissingRequestTokenError() + # merge request token with verifier + token = {} + token.update(request_token) + token.update(kwargs) + client.token = token + params = self.access_token_params or {} + token = await client.fetch_access_token(self.access_token_url, **params) + return token + + +class AsyncOAuth2Mixin(OAuth2Base): + async def _on_update_token(self, token, refresh_token=None, access_token=None): + if self._update_token: + await self._update_token( + token, + refresh_token=refresh_token, + access_token=access_token, + ) + + async def load_server_metadata(self): + if self._server_metadata_url and '_loaded_at' not in self.server_metadata: + async with self.client_cls(**self.client_kwargs) as client: + resp = await client.request('GET', self._server_metadata_url, withhold_token=True) + resp.raise_for_status() + metadata = resp.json() + metadata['_loaded_at'] = time.time() + self.server_metadata.update(metadata) + return self.server_metadata + + async def request(self, method, url, token=None, **kwargs): + metadata = await self.load_server_metadata() + async with self._get_oauth_client(**metadata) as session: + return await _http_request(self, session, method, url, token, kwargs) + + async def create_authorization_url(self, redirect_uri=None, **kwargs): + """Generate the authorization url and state for HTTP redirect. + + :param redirect_uri: Callback or redirect URI for authorization. + :param kwargs: Extra parameters to include. + :return: dict + """ + metadata = await self.load_server_metadata() + authorization_endpoint = self.authorize_url or metadata.get('authorization_endpoint') + if not authorization_endpoint: + raise RuntimeError('Missing "authorize_url" value') + + if self.authorize_params: + kwargs.update(self.authorize_params) + + async with self._get_oauth_client(**metadata) as client: + client.redirect_uri = redirect_uri + return self._create_oauth2_authorization_url( + client, authorization_endpoint, **kwargs) + + async def fetch_access_token(self, redirect_uri=None, **kwargs): + """Fetch access token in the final step. + + :param redirect_uri: Callback or Redirect URI that is used in + previous :meth:`authorize_redirect`. + :param kwargs: Extra parameters to fetch access token. + :return: A token dict. + """ + metadata = await self.load_server_metadata() + token_endpoint = self.access_token_url or metadata.get('token_endpoint') + async with self._get_oauth_client(**metadata) as client: + if redirect_uri is not None: + client.redirect_uri = redirect_uri + params = {} + if self.access_token_params: + params.update(self.access_token_params) + params.update(kwargs) + token = await client.fetch_token(token_endpoint, **params) + return token + + +async def _http_request(ctx, session, method, url, token, kwargs): + request = kwargs.pop('request', None) + withhold_token = kwargs.get('withhold_token') + if ctx.api_base_url and not url.startswith(('https://', 'http://')): + url = urlparse.urljoin(ctx.api_base_url, url) + + if withhold_token: + return await session.request(method, url, **kwargs) + + if token is None and ctx._fetch_token and request: + token = await ctx._fetch_token(request) + if token is None: + raise MissingTokenError() + + session.token = token + return await session.request(method, url, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/async_openid.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/async_openid.py new file mode 100644 index 0000000000000000000000000000000000000000..68100f2f60aa47267e353ed19228586ebf56458e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/async_openid.py @@ -0,0 +1,79 @@ +from authlib.jose import JsonWebToken, JsonWebKey +from authlib.oidc.core import UserInfo, CodeIDToken, ImplicitIDToken + +__all__ = ['AsyncOpenIDMixin'] + + +class AsyncOpenIDMixin: + async def fetch_jwk_set(self, force=False): + metadata = await self.load_server_metadata() + jwk_set = metadata.get('jwks') + if jwk_set and not force: + return jwk_set + + uri = metadata.get('jwks_uri') + if not uri: + raise RuntimeError('Missing "jwks_uri" in metadata') + + async with self.client_cls(**self.client_kwargs) as client: + resp = await client.request('GET', uri, withhold_token=True) + resp.raise_for_status() + jwk_set = resp.json() + + self.server_metadata['jwks'] = jwk_set + return jwk_set + + async def userinfo(self, **kwargs): + """Fetch user info from ``userinfo_endpoint``.""" + metadata = await self.load_server_metadata() + resp = await self.get(metadata['userinfo_endpoint'], **kwargs) + resp.raise_for_status() + data = resp.json() + return UserInfo(data) + + async def parse_id_token(self, token, nonce, claims_options=None): + """Return an instance of UserInfo from token's ``id_token``.""" + claims_params = dict( + nonce=nonce, + client_id=self.client_id, + ) + if 'access_token' in token: + claims_params['access_token'] = token['access_token'] + claims_cls = CodeIDToken + else: + claims_cls = ImplicitIDToken + + metadata = await self.load_server_metadata() + if claims_options is None and 'issuer' in metadata: + claims_options = {'iss': {'values': [metadata['issuer']]}} + + alg_values = metadata.get('id_token_signing_alg_values_supported') + if not alg_values: + alg_values = ['RS256'] + + jwt = JsonWebToken(alg_values) + + jwk_set = await self.fetch_jwk_set() + try: + claims = jwt.decode( + token['id_token'], + key=JsonWebKey.import_key_set(jwk_set), + claims_cls=claims_cls, + claims_options=claims_options, + claims_params=claims_params, + ) + except ValueError: + jwk_set = await self.fetch_jwk_set(force=True) + claims = jwt.decode( + token['id_token'], + key=JsonWebKey.import_key_set(jwk_set), + claims_cls=claims_cls, + claims_options=claims_options, + claims_params=claims_params, + ) + + # https://github.com/lepture/authlib/issues/259 + if claims.get('nonce_supported') is False: + claims.params['nonce'] = None + claims.validate(leeway=120) + return UserInfo(claims) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/errors.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..bb4dd2b12dc0c80922596eedb460d12c288d936a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/errors.py @@ -0,0 +1,30 @@ +from authlib.common.errors import AuthlibBaseError + + +class OAuthError(AuthlibBaseError): + error = 'oauth_error' + + +class MissingRequestTokenError(OAuthError): + error = 'missing_request_token' + + +class MissingTokenError(OAuthError): + error = 'missing_token' + + +class TokenExpiredError(OAuthError): + error = 'token_expired' + + +class InvalidTokenError(OAuthError): + error = 'token_invalid' + + +class UnsupportedTokenTypeError(OAuthError): + error = 'unsupported_token_type' + + +class MismatchingStateError(OAuthError): + error = 'mismatching_state' + description = 'CSRF Warning! State not equal in request and response.' diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/framework_integration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/framework_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..9243e8f0c3be37b8a2f1510f48cfe7234cfb4c1f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/framework_integration.py @@ -0,0 +1,64 @@ +import json +import time + + +class FrameworkIntegration: + expires_in = 3600 + + def __init__(self, name, cache=None): + self.name = name + self.cache = cache + + def _get_cache_data(self, key): + value = self.cache.get(key) + if not value: + return None + try: + return json.loads(value) + except (TypeError, ValueError): + return None + + def _clear_session_state(self, session): + now = time.time() + for key in dict(session): + if '_authlib_' in key: + # TODO: remove in future + session.pop(key) + elif key.startswith('_state_'): + value = session[key] + exp = value.get('exp') + if not exp or exp < now: + session.pop(key) + + def get_state_data(self, session, state): + key = f'_state_{self.name}_{state}' + if self.cache: + value = self._get_cache_data(key) + else: + value = session.get(key) + if value: + return value.get('data') + return None + + def set_state_data(self, session, state, data): + key = f'_state_{self.name}_{state}' + if self.cache: + self.cache.set(key, json.dumps({'data': data}), self.expires_in) + else: + now = time.time() + session[key] = {'data': data, 'exp': now + self.expires_in} + + def clear_state_data(self, session, state): + key = f'_state_{self.name}_{state}' + if self.cache: + self.cache.delete(key) + else: + session.pop(key, None) + self._clear_session_state(session) + + def update_token(self, token, refresh_token=None, access_token=None): + raise NotImplementedError() + + @staticmethod + def load_config(oauth, name, params): + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/registry.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..68d1be5d2af6a82285504b3c0b0c4a0fc9a072ef --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/registry.py @@ -0,0 +1,131 @@ +import functools +from .framework_integration import FrameworkIntegration + +__all__ = ['BaseOAuth'] + + +OAUTH_CLIENT_PARAMS = ( + 'client_id', 'client_secret', + 'request_token_url', 'request_token_params', + 'access_token_url', 'access_token_params', + 'refresh_token_url', 'refresh_token_params', + 'authorize_url', 'authorize_params', + 'api_base_url', 'client_kwargs', + 'server_metadata_url', +) + + +class BaseOAuth: + """Registry for oauth clients. + + Create an instance for registry:: + + oauth = OAuth() + """ + oauth1_client_cls = None + oauth2_client_cls = None + framework_integration_cls = FrameworkIntegration + + def __init__(self, cache=None, fetch_token=None, update_token=None): + self._registry = {} + self._clients = {} + self.cache = cache + self.fetch_token = fetch_token + self.update_token = update_token + + def create_client(self, name): + """Create or get the given named OAuth client. For instance, the + OAuth registry has ``.register`` a twitter client, developers may + access the client with:: + + client = oauth.create_client('twitter') + + :param: name: Name of the remote application + :return: OAuth remote app + """ + if name in self._clients: + return self._clients[name] + + if name not in self._registry: + return None + + overwrite, config = self._registry[name] + client_cls = config.pop('client_cls', None) + + if client_cls and client_cls.OAUTH_APP_CONFIG: + kwargs = client_cls.OAUTH_APP_CONFIG + kwargs.update(config) + else: + kwargs = config + + kwargs = self.generate_client_kwargs(name, overwrite, **kwargs) + framework = self.framework_integration_cls(name, self.cache) + if client_cls: + client = client_cls(framework, name, **kwargs) + elif kwargs.get('request_token_url'): + client = self.oauth1_client_cls(framework, name, **kwargs) + else: + client = self.oauth2_client_cls(framework, name, **kwargs) + + self._clients[name] = client + return client + + def register(self, name, overwrite=False, **kwargs): + """Registers a new remote application. + + :param name: Name of the remote application. + :param overwrite: Overwrite existing config with framework settings. + :param kwargs: Parameters for :class:`RemoteApp`. + + Find parameters for the given remote app class. When a remote app is + registered, it can be accessed with *named* attribute:: + + oauth.register('twitter', client_id='', ...) + oauth.twitter.get('timeline') + """ + self._registry[name] = (overwrite, kwargs) + return self.create_client(name) + + def generate_client_kwargs(self, name, overwrite, **kwargs): + fetch_token = kwargs.pop('fetch_token', None) + update_token = kwargs.pop('update_token', None) + + config = self.load_config(name, OAUTH_CLIENT_PARAMS) + if config: + kwargs = _config_client(config, kwargs, overwrite) + + if not fetch_token and self.fetch_token: + fetch_token = functools.partial(self.fetch_token, name) + + kwargs['fetch_token'] = fetch_token + + if not kwargs.get('request_token_url'): + if not update_token and self.update_token: + update_token = functools.partial(self.update_token, name) + + kwargs['update_token'] = update_token + return kwargs + + def load_config(self, name, params): + return self.framework_integration_cls.load_config(self, name, params) + + def __getattr__(self, key): + try: + return object.__getattribute__(self, key) + except AttributeError: + if key in self._registry: + return self.create_client(key) + raise AttributeError('No such client: %s' % key) + + +def _config_client(config, kwargs, overwrite): + for k in OAUTH_CLIENT_PARAMS: + v = config.get(k, None) + if k not in kwargs: + kwargs[k] = v + elif overwrite and v: + if isinstance(kwargs[k], dict): + kwargs[k].update(v) + else: + kwargs[k] = v + return kwargs diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/sync_app.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/sync_app.py new file mode 100644 index 0000000000000000000000000000000000000000..50fa27a7dd1ddceef8c25b59f557a23c4ab53ace --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/sync_app.py @@ -0,0 +1,343 @@ +import time +import logging +from authlib.common.urls import urlparse +from authlib.consts import default_user_agent +from authlib.common.security import generate_token +from .errors import ( + MismatchingStateError, + MissingRequestTokenError, + MissingTokenError, +) + +log = logging.getLogger(__name__) + + +class BaseApp: + client_cls = None + OAUTH_APP_CONFIG = None + + def request(self, method, url, token=None, **kwargs): + raise NotImplementedError() + + def get(self, url, **kwargs): + """Invoke GET http request. + + If ``api_base_url`` configured, shortcut is available:: + + client.get('users/lepture') + """ + return self.request('GET', url, **kwargs) + + def post(self, url, **kwargs): + """Invoke POST http request. + + If ``api_base_url`` configured, shortcut is available:: + + client.post('timeline', json={'text': 'Hi'}) + """ + return self.request('POST', url, **kwargs) + + def patch(self, url, **kwargs): + """Invoke PATCH http request. + + If ``api_base_url`` configured, shortcut is available:: + + client.patch('profile', json={'name': 'Hsiaoming Yang'}) + """ + return self.request('PATCH', url, **kwargs) + + def put(self, url, **kwargs): + """Invoke PUT http request. + + If ``api_base_url`` configured, shortcut is available:: + + client.put('profile', json={'name': 'Hsiaoming Yang'}) + """ + return self.request('PUT', url, **kwargs) + + def delete(self, url, **kwargs): + """Invoke DELETE http request. + + If ``api_base_url`` configured, shortcut is available:: + + client.delete('posts/123') + """ + return self.request('DELETE', url, **kwargs) + + +class _RequestMixin: + def _get_requested_token(self, request): + if self._fetch_token and request: + return self._fetch_token(request) + + def _send_token_request(self, session, method, url, token, kwargs): + request = kwargs.pop('request', None) + withhold_token = kwargs.get('withhold_token') + if self.api_base_url and not url.startswith(('https://', 'http://')): + url = urlparse.urljoin(self.api_base_url, url) + + if withhold_token: + return session.request(method, url, **kwargs) + + if token is None: + token = self._get_requested_token(request) + + if token is None: + raise MissingTokenError() + + session.token = token + return session.request(method, url, **kwargs) + + +class OAuth1Base: + client_cls = None + + def __init__( + self, framework, name=None, fetch_token=None, + client_id=None, client_secret=None, + request_token_url=None, request_token_params=None, + access_token_url=None, access_token_params=None, + authorize_url=None, authorize_params=None, + api_base_url=None, client_kwargs=None, user_agent=None, **kwargs): + self.framework = framework + self.name = name + self.client_id = client_id + self.client_secret = client_secret + self.request_token_url = request_token_url + self.request_token_params = request_token_params + self.access_token_url = access_token_url + self.access_token_params = access_token_params + self.authorize_url = authorize_url + self.authorize_params = authorize_params + self.api_base_url = api_base_url + self.client_kwargs = client_kwargs or {} + + self._fetch_token = fetch_token + self._user_agent = user_agent or default_user_agent + self._kwargs = kwargs + + def _get_oauth_client(self): + session = self.client_cls(self.client_id, self.client_secret, **self.client_kwargs) + session.headers['User-Agent'] = self._user_agent + return session + + +class OAuth1Mixin(_RequestMixin, OAuth1Base): + def request(self, method, url, token=None, **kwargs): + with self._get_oauth_client() as session: + return self._send_token_request(session, method, url, token, kwargs) + + def create_authorization_url(self, redirect_uri=None, **kwargs): + """Generate the authorization url and state for HTTP redirect. + + :param redirect_uri: Callback or redirect URI for authorization. + :param kwargs: Extra parameters to include. + :return: dict + """ + if not self.authorize_url: + raise RuntimeError('Missing "authorize_url" value') + + if self.authorize_params: + kwargs.update(self.authorize_params) + + with self._get_oauth_client() as client: + client.redirect_uri = redirect_uri + params = self.request_token_params or {} + request_token = client.fetch_request_token(self.request_token_url, **params) + log.debug(f'Fetch request token: {request_token!r}') + url = client.create_authorization_url(self.authorize_url, **kwargs) + state = request_token['oauth_token'] + return {'url': url, 'request_token': request_token, 'state': state} + + def fetch_access_token(self, request_token=None, **kwargs): + """Fetch access token in one step. + + :param request_token: A previous request token for OAuth 1. + :param kwargs: Extra parameters to fetch access token. + :return: A token dict. + """ + with self._get_oauth_client() as client: + if request_token is None: + raise MissingRequestTokenError() + # merge request token with verifier + token = {} + token.update(request_token) + token.update(kwargs) + client.token = token + params = self.access_token_params or {} + token = client.fetch_access_token(self.access_token_url, **params) + return token + + +class OAuth2Base: + client_cls = None + + def __init__( + self, framework, name=None, fetch_token=None, update_token=None, + client_id=None, client_secret=None, + access_token_url=None, access_token_params=None, + authorize_url=None, authorize_params=None, + api_base_url=None, client_kwargs=None, server_metadata_url=None, + compliance_fix=None, client_auth_methods=None, user_agent=None, **kwargs): + self.framework = framework + self.name = name + self.client_id = client_id + self.client_secret = client_secret + self.access_token_url = access_token_url + self.access_token_params = access_token_params + self.authorize_url = authorize_url + self.authorize_params = authorize_params + self.api_base_url = api_base_url + self.client_kwargs = client_kwargs or {} + + self.compliance_fix = compliance_fix + self.client_auth_methods = client_auth_methods + self._fetch_token = fetch_token + self._update_token = update_token + self._user_agent = user_agent or default_user_agent + + self._server_metadata_url = server_metadata_url + self.server_metadata = kwargs + + def _on_update_token(self, token, refresh_token=None, access_token=None): + raise NotImplementedError() + + def _get_oauth_client(self, **metadata): + client_kwargs = {} + client_kwargs.update(self.client_kwargs) + client_kwargs.update(metadata) + + if self.authorize_url: + client_kwargs['authorization_endpoint'] = self.authorize_url + if self.access_token_url: + client_kwargs['token_endpoint'] = self.access_token_url + + session = self.client_cls( + client_id=self.client_id, + client_secret=self.client_secret, + update_token=self._on_update_token, + **client_kwargs + ) + if self.client_auth_methods: + for f in self.client_auth_methods: + session.register_client_auth_method(f) + + if self.compliance_fix: + self.compliance_fix(session) + + session.headers['User-Agent'] = self._user_agent + return session + + @staticmethod + def _format_state_params(state_data, params): + if state_data is None: + raise MismatchingStateError() + + code_verifier = state_data.get('code_verifier') + if code_verifier: + params['code_verifier'] = code_verifier + + redirect_uri = state_data.get('redirect_uri') + if redirect_uri: + params['redirect_uri'] = redirect_uri + return params + + @staticmethod + def _create_oauth2_authorization_url(client, authorization_endpoint, **kwargs): + rv = {} + if client.code_challenge_method: + code_verifier = kwargs.get('code_verifier') + if not code_verifier: + code_verifier = generate_token(48) + kwargs['code_verifier'] = code_verifier + rv['code_verifier'] = code_verifier + log.debug(f'Using code_verifier: {code_verifier!r}') + + scope = kwargs.get('scope', client.scope) + if scope and 'openid' in scope.split(): + # this is an OpenID Connect service + nonce = kwargs.get('nonce') + if not nonce: + nonce = generate_token(20) + kwargs['nonce'] = nonce + rv['nonce'] = nonce + + url, state = client.create_authorization_url( + authorization_endpoint, **kwargs) + rv['url'] = url + rv['state'] = state + return rv + + +class OAuth2Mixin(_RequestMixin, OAuth2Base): + def _on_update_token(self, token, refresh_token=None, access_token=None): + if callable(self._update_token): + self._update_token( + token, + refresh_token=refresh_token, + access_token=access_token, + ) + self.framework.update_token( + token, + refresh_token=refresh_token, + access_token=access_token, + ) + + def request(self, method, url, token=None, **kwargs): + metadata = self.load_server_metadata() + with self._get_oauth_client(**metadata) as session: + return self._send_token_request(session, method, url, token, kwargs) + + def load_server_metadata(self): + if self._server_metadata_url and '_loaded_at' not in self.server_metadata: + with self.client_cls(**self.client_kwargs) as session: + resp = session.request('GET', self._server_metadata_url, withhold_token=True) + resp.raise_for_status() + metadata = resp.json() + + metadata['_loaded_at'] = time.time() + self.server_metadata.update(metadata) + return self.server_metadata + + def create_authorization_url(self, redirect_uri=None, **kwargs): + """Generate the authorization url and state for HTTP redirect. + + :param redirect_uri: Callback or redirect URI for authorization. + :param kwargs: Extra parameters to include. + :return: dict + """ + metadata = self.load_server_metadata() + authorization_endpoint = self.authorize_url or metadata.get('authorization_endpoint') + + if not authorization_endpoint: + raise RuntimeError('Missing "authorize_url" value') + + if self.authorize_params: + kwargs.update(self.authorize_params) + + + with self._get_oauth_client(**metadata) as client: + if redirect_uri is not None: + client.redirect_uri = redirect_uri + return self._create_oauth2_authorization_url( + client, authorization_endpoint, **kwargs) + + def fetch_access_token(self, redirect_uri=None, **kwargs): + """Fetch access token in the final step. + + :param redirect_uri: Callback or Redirect URI that is used in + previous :meth:`authorize_redirect`. + :param kwargs: Extra parameters to fetch access token. + :return: A token dict. + """ + metadata = self.load_server_metadata() + token_endpoint = self.access_token_url or metadata.get('token_endpoint') + with self._get_oauth_client(**metadata) as client: + if redirect_uri is not None: + client.redirect_uri = redirect_uri + params = {} + if self.access_token_params: + params.update(self.access_token_params) + params.update(kwargs) + token = client.fetch_token(token_endpoint, **params) + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/sync_openid.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/sync_openid.py new file mode 100644 index 0000000000000000000000000000000000000000..ac51907a115d7f2f09b09c35e3109ee131479274 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/base_client/sync_openid.py @@ -0,0 +1,77 @@ +from authlib.jose import jwt, JsonWebToken, JsonWebKey +from authlib.oidc.core import UserInfo, CodeIDToken, ImplicitIDToken + + +class OpenIDMixin: + def fetch_jwk_set(self, force=False): + metadata = self.load_server_metadata() + jwk_set = metadata.get('jwks') + if jwk_set and not force: + return jwk_set + + uri = metadata.get('jwks_uri') + if not uri: + raise RuntimeError('Missing "jwks_uri" in metadata') + + with self.client_cls(**self.client_kwargs) as session: + resp = session.request('GET', uri, withhold_token=True) + resp.raise_for_status() + jwk_set = resp.json() + + self.server_metadata['jwks'] = jwk_set + return jwk_set + + def userinfo(self, **kwargs): + """Fetch user info from ``userinfo_endpoint``.""" + metadata = self.load_server_metadata() + resp = self.get(metadata['userinfo_endpoint'], **kwargs) + resp.raise_for_status() + data = resp.json() + return UserInfo(data) + + def parse_id_token(self, token, nonce, claims_options=None, leeway=120): + """Return an instance of UserInfo from token's ``id_token``.""" + if 'id_token' not in token: + return None + + def load_key(header, _): + jwk_set = JsonWebKey.import_key_set(self.fetch_jwk_set()) + try: + return jwk_set.find_by_kid(header.get('kid')) + except ValueError: + # re-try with new jwk set + jwk_set = JsonWebKey.import_key_set(self.fetch_jwk_set(force=True)) + return jwk_set.find_by_kid(header.get('kid')) + + claims_params = dict( + nonce=nonce, + client_id=self.client_id, + ) + if 'access_token' in token: + claims_params['access_token'] = token['access_token'] + claims_cls = CodeIDToken + else: + claims_cls = ImplicitIDToken + + metadata = self.load_server_metadata() + if claims_options is None and 'issuer' in metadata: + claims_options = {'iss': {'values': [metadata['issuer']]}} + + alg_values = metadata.get('id_token_signing_alg_values_supported') + if alg_values: + _jwt = JsonWebToken(alg_values) + else: + _jwt = jwt + + claims = _jwt.decode( + token['id_token'], key=load_key, + claims_cls=claims_cls, + claims_options=claims_options, + claims_params=claims_params, + ) + # https://github.com/lepture/authlib/issues/259 + if claims.get('nonce_supported') is False: + claims.params['nonce'] = None + + claims.validate(leeway=leeway) + return UserInfo(claims) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_client/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5839c9456b81cfe3e6ce14c9f3abe4d0cf8a33ad --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_client/__init__.py @@ -0,0 +1,19 @@ +# flake8: noqa + +from .integration import DjangoIntegration, token_update +from .apps import DjangoOAuth1App, DjangoOAuth2App +from ..base_client import BaseOAuth, OAuthError + + +class OAuth(BaseOAuth): + oauth1_client_cls = DjangoOAuth1App + oauth2_client_cls = DjangoOAuth2App + framework_integration_cls = DjangoIntegration + + +__all__ = [ + 'OAuth', + 'DjangoOAuth1App', 'DjangoOAuth2App', + 'DjangoIntegration', + 'token_update', 'OAuthError', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_client/apps.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_client/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..07bdf7196a731bd1a85c55d8b7158a0b799263e9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_client/apps.py @@ -0,0 +1,87 @@ +from django.http import HttpResponseRedirect +from ..requests_client import OAuth1Session, OAuth2Session +from ..base_client import ( + BaseApp, OAuthError, + OAuth1Mixin, OAuth2Mixin, OpenIDMixin, +) + + +class DjangoAppMixin: + def save_authorize_data(self, request, **kwargs): + state = kwargs.pop('state', None) + if state: + self.framework.set_state_data(request.session, state, kwargs) + else: + raise RuntimeError('Missing state value') + + def authorize_redirect(self, request, redirect_uri=None, **kwargs): + """Create a HTTP Redirect for Authorization Endpoint. + + :param request: HTTP request instance from Django view. + :param redirect_uri: Callback or redirect URI for authorization. + :param kwargs: Extra parameters to include. + :return: A HTTP redirect response. + """ + rv = self.create_authorization_url(redirect_uri, **kwargs) + self.save_authorize_data(request, redirect_uri=redirect_uri, **rv) + return HttpResponseRedirect(rv['url']) + + +class DjangoOAuth1App(DjangoAppMixin, OAuth1Mixin, BaseApp): + client_cls = OAuth1Session + + def authorize_access_token(self, request, **kwargs): + """Fetch access token in one step. + + :param request: HTTP request instance from Django view. + :return: A token dict. + """ + params = request.GET.dict() + state = params.get('oauth_token') + if not state: + raise OAuthError(description='Missing "oauth_token" parameter') + + data = self.framework.get_state_data(request.session, state) + if not data: + raise OAuthError(description='Missing "request_token" in temporary data') + + params['request_token'] = data['request_token'] + params.update(kwargs) + self.framework.clear_state_data(request.session, state) + return self.fetch_access_token(**params) + + +class DjangoOAuth2App(DjangoAppMixin, OAuth2Mixin, OpenIDMixin, BaseApp): + client_cls = OAuth2Session + + def authorize_access_token(self, request, **kwargs): + """Fetch access token in one step. + + :param request: HTTP request instance from Django view. + :return: A token dict. + """ + if request.method == 'GET': + error = request.GET.get('error') + if error: + description = request.GET.get('error_description') + raise OAuthError(error=error, description=description) + params = { + 'code': request.GET.get('code'), + 'state': request.GET.get('state'), + } + else: + params = { + 'code': request.POST.get('code'), + 'state': request.POST.get('state'), + } + + claims_options = kwargs.pop('claims_options', None) + state_data = self.framework.get_state_data(request.session, params.get('state')) + self.framework.clear_state_data(request.session, params.get('state')) + params = self._format_state_params(state_data, params) + token = self.fetch_access_token(**params, **kwargs) + + if 'id_token' in token and 'nonce' in state_data: + userinfo = self.parse_id_token(token, nonce=state_data['nonce'], claims_options=claims_options) + token['userinfo'] = userinfo + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_client/integration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_client/integration.py new file mode 100644 index 0000000000000000000000000000000000000000..2ff03deab3bb7a744c39a74d3e6c7f7573ba42a7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_client/integration.py @@ -0,0 +1,22 @@ +from django.conf import settings +from django.dispatch import Signal +from ..base_client import FrameworkIntegration + +token_update = Signal() + + +class DjangoIntegration(FrameworkIntegration): + def update_token(self, token, refresh_token=None, access_token=None): + token_update.send( + sender=self.__class__, + name=self.name, + token=token, + refresh_token=refresh_token, + access_token=access_token, + ) + + @staticmethod + def load_config(oauth, name, params): + config = getattr(settings, 'AUTHLIB_OAUTH_CLIENTS', None) + if config: + return config.get(name) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..39f0e13078ac325d81378470bf2eb35e10773a81 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/__init__.py @@ -0,0 +1,9 @@ +# flake8: noqa + +from .authorization_server import ( + BaseServer, CacheAuthorizationServer +) +from .resource_protector import ResourceProtector + + +__all__ = ['BaseServer', 'CacheAuthorizationServer', 'ResourceProtector'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/authorization_server.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/authorization_server.py new file mode 100644 index 0000000000000000000000000000000000000000..70c2b6bc5ccc4e36c1c701a45f41ddcad4a6e227 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/authorization_server.py @@ -0,0 +1,125 @@ +import logging +from authlib.oauth1 import ( + OAuth1Request, + AuthorizationServer as _AuthorizationServer, +) +from authlib.oauth1 import TemporaryCredential +from authlib.common.security import generate_token +from authlib.common.urls import url_encode +from django.core.cache import cache +from django.conf import settings +from django.http import HttpResponse +from .nonce import exists_nonce_in_cache + +log = logging.getLogger(__name__) + + +class BaseServer(_AuthorizationServer): + def __init__(self, client_model, token_model, token_generator=None): + self.client_model = client_model + self.token_model = token_model + + if token_generator is None: + def token_generator(): + return { + 'oauth_token': generate_token(42), + 'oauth_token_secret': generate_token(48) + } + + self.token_generator = token_generator + self._config = getattr(settings, 'AUTHLIB_OAUTH1_PROVIDER', {}) + self._nonce_expires_in = self._config.get('nonce_expires_in', 86400) + methods = self._config.get('signature_methods') + if methods: + self.SUPPORTED_SIGNATURE_METHODS = methods + + def get_client_by_id(self, client_id): + try: + return self.client_model.objects.get(client_id=client_id) + except self.client_model.DoesNotExist: + return None + + def exists_nonce(self, nonce, request): + return exists_nonce_in_cache(nonce, request, self._nonce_expires_in) + + def create_token_credential(self, request): + temporary_credential = request.credential + token = self.token_generator() + item = self.token_model( + oauth_token=token['oauth_token'], + oauth_token_secret=token['oauth_token_secret'], + user_id=temporary_credential.get_user_id(), + client_id=temporary_credential.get_client_id() + ) + item.save() + return item + + def check_authorization_request(self, request): + req = self.create_oauth1_request(request) + self.validate_authorization_request(req) + return req + + def create_oauth1_request(self, request): + if request.method == 'POST': + body = request.POST.dict() + else: + body = None + url = request.build_absolute_uri() + return OAuth1Request(request.method, url, body, request.headers) + + def handle_response(self, status_code, payload, headers): + resp = HttpResponse(url_encode(payload), status=status_code) + for k, v in headers: + resp[k] = v + return resp + + +class CacheAuthorizationServer(BaseServer): + def __init__(self, client_model, token_model, token_generator=None): + super().__init__( + client_model, token_model, token_generator) + self._temporary_expires_in = self._config.get( + 'temporary_credential_expires_in', 86400) + self._temporary_credential_key_prefix = self._config.get( + 'temporary_credential_key_prefix', 'temporary_credential:') + + def create_temporary_credential(self, request): + key_prefix = self._temporary_credential_key_prefix + token = self.token_generator() + + client_id = request.client_id + redirect_uri = request.redirect_uri + key = key_prefix + token['oauth_token'] + token['client_id'] = client_id + if redirect_uri: + token['oauth_callback'] = redirect_uri + + cache.set(key, token, timeout=self._temporary_expires_in) + return TemporaryCredential(token) + + def get_temporary_credential(self, request): + if not request.token: + return None + + key_prefix = self._temporary_credential_key_prefix + key = key_prefix + request.token + value = cache.get(key) + if value: + return TemporaryCredential(value) + + def delete_temporary_credential(self, request): + if request.token: + key_prefix = self._temporary_credential_key_prefix + key = key_prefix + request.token + cache.delete(key) + + def create_authorization_verifier(self, request): + key_prefix = self._temporary_credential_key_prefix + verifier = generate_token(36) + credential = request.credential + user = request.user + key = key_prefix + credential.get_oauth_token() + credential['oauth_verifier'] = verifier + credential['user_id'] = user.pk + cache.set(key, credential, timeout=self._temporary_expires_in) + return verifier diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/nonce.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/nonce.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd70e3123d96a1bc996b914db300f43c31cb009 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/nonce.py @@ -0,0 +1,15 @@ +from django.core.cache import cache + + +def exists_nonce_in_cache(nonce, request, timeout): + key_prefix = 'nonce:' + timestamp = request.timestamp + client_id = request.client_id + token = request.token + key = f'{key_prefix}{nonce}-{timestamp}-{client_id}' + if token: + key = f'{key}-{token}' + + rv = bool(cache.get(key)) + cache.set(key, 1, timeout=timeout) + return rv diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/resource_protector.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/resource_protector.py new file mode 100644 index 0000000000000000000000000000000000000000..77f3d81f1383f9aacd8d7617b7f03f7aa3ead1e8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth1/resource_protector.py @@ -0,0 +1,64 @@ +import functools +from authlib.oauth1.errors import OAuth1Error +from authlib.oauth1 import ResourceProtector as _ResourceProtector +from django.http import JsonResponse +from django.conf import settings +from .nonce import exists_nonce_in_cache + + +class ResourceProtector(_ResourceProtector): + def __init__(self, client_model, token_model): + self.client_model = client_model + self.token_model = token_model + + config = getattr(settings, 'AUTHLIB_OAUTH1_PROVIDER', {}) + methods = config.get('signature_methods', []) + if methods and isinstance(methods, (list, tuple)): + self.SUPPORTED_SIGNATURE_METHODS = methods + + self._nonce_expires_in = config.get('nonce_expires_in', 86400) + + def get_client_by_id(self, client_id): + try: + return self.client_model.objects.get(client_id=client_id) + except self.client_model.DoesNotExist: + return None + + def get_token_credential(self, request): + try: + return self.token_model.objects.get( + client_id=request.client_id, + oauth_token=request.token + ) + except self.token_model.DoesNotExist: + return None + + def exists_nonce(self, nonce, request): + return exists_nonce_in_cache(nonce, request, self._nonce_expires_in) + + def acquire_credential(self, request): + if request.method in ['POST', 'PUT']: + body = request.POST.dict() + else: + body = None + + url = request.build_absolute_uri() + req = self.validate_request(request.method, url, body, request.headers) + return req.credential + + def __call__(self, realm=None): + def wrapper(f): + @functools.wraps(f) + def decorated(request, *args, **kwargs): + try: + credential = self.acquire_credential(request) + request.oauth1_credential = credential + except OAuth1Error as error: + body = dict(error.get_body()) + resp = JsonResponse(body, status=error.status_code) + resp['Cache-Control'] = 'no-store' + resp['Pragma'] = 'no-cache' + return resp + return f(request, *args, **kwargs) + return decorated + return wrapper diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..05c1fdfe94bb5721388a48bc5791e6ee18f7a2fa --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/__init__.py @@ -0,0 +1,10 @@ +# flake8: noqa + +from .authorization_server import AuthorizationServer +from .resource_protector import ResourceProtector, BearerTokenValidator +from .endpoints import RevocationEndpoint +from .signals import ( + client_authenticated, + token_authenticated, + token_revoked +) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/authorization_server.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/authorization_server.py new file mode 100644 index 0000000000000000000000000000000000000000..08a275950849827797a7a5bdd97ade2fbcb5cf92 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/authorization_server.py @@ -0,0 +1,118 @@ +from django.http import HttpResponse +from django.utils.module_loading import import_string +from django.conf import settings +from authlib.oauth2 import ( + AuthorizationServer as _AuthorizationServer, +) +from authlib.oauth2.rfc6750 import BearerTokenGenerator +from authlib.common.security import generate_token as _generate_token +from authlib.common.encoding import json_dumps +from .requests import DjangoOAuth2Request, DjangoJsonRequest +from .signals import client_authenticated, token_revoked + + +class AuthorizationServer(_AuthorizationServer): + """Django implementation of :class:`authlib.oauth2.rfc6749.AuthorizationServer`. + Initialize it with client model and token model:: + + from authlib.integrations.django_oauth2 import AuthorizationServer + from your_project.models import OAuth2Client, OAuth2Token + + server = AuthorizationServer(OAuth2Client, OAuth2Token) + """ + + def __init__(self, client_model, token_model): + self.config = getattr(settings, 'AUTHLIB_OAUTH2_PROVIDER', {}) + self.client_model = client_model + self.token_model = token_model + scopes_supported = self.config.get('scopes_supported') + super().__init__(scopes_supported=scopes_supported) + # add default token generator + self.register_token_generator('default', self.create_bearer_token_generator()) + + def query_client(self, client_id): + """Default method for ``AuthorizationServer.query_client``. Developers MAY + rewrite this function to meet their own needs. + """ + try: + return self.client_model.objects.get(client_id=client_id) + except self.client_model.DoesNotExist: + return None + + def save_token(self, token, request): + """Default method for ``AuthorizationServer.save_token``. Developers MAY + rewrite this function to meet their own needs. + """ + client = request.client + if request.user: + user_id = request.user.pk + else: + user_id = client.user_id + item = self.token_model( + client_id=client.client_id, + user_id=user_id, + **token + ) + item.save() + return item + + def create_oauth2_request(self, request): + return DjangoOAuth2Request(request) + + def create_json_request(self, request): + return DjangoJsonRequest(request) + + def handle_response(self, status_code, payload, headers): + if isinstance(payload, dict): + payload = json_dumps(payload) + resp = HttpResponse(payload, status=status_code) + for k, v in headers: + resp[k] = v + return resp + + def send_signal(self, name, *args, **kwargs): + if name == 'after_authenticate_client': + client_authenticated.send(sender=self.__class__, *args, **kwargs) + elif name == 'after_revoke_token': + token_revoked.send(sender=self.__class__, *args, **kwargs) + + def create_bearer_token_generator(self): + """Default method to create BearerToken generator.""" + conf = self.config.get('access_token_generator', True) + access_token_generator = create_token_generator(conf, 42) + + conf = self.config.get('refresh_token_generator', False) + refresh_token_generator = create_token_generator(conf, 48) + + conf = self.config.get('token_expires_in') + expires_generator = create_token_expires_in_generator(conf) + + return BearerTokenGenerator( + access_token_generator=access_token_generator, + refresh_token_generator=refresh_token_generator, + expires_generator=expires_generator, + ) + + +def create_token_generator(token_generator_conf, length=42): + if callable(token_generator_conf): + return token_generator_conf + + if isinstance(token_generator_conf, str): + return import_string(token_generator_conf) + elif token_generator_conf is True: + def token_generator(*args, **kwargs): + return _generate_token(length) + return token_generator + + +def create_token_expires_in_generator(expires_in_conf=None): + data = {} + data.update(BearerTokenGenerator.GRANT_TYPES_EXPIRES_IN) + if expires_in_conf: + data.update(expires_in_conf) + + def expires_in(client, grant_type): + return data.get(grant_type, BearerTokenGenerator.DEFAULT_EXPIRES_IN) + + return expires_in diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/endpoints.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/endpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..686675d57e0906328c54c49f0779345a245751a2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/endpoints.py @@ -0,0 +1,56 @@ +from authlib.oauth2.rfc7009 import RevocationEndpoint as _RevocationEndpoint + + +class RevocationEndpoint(_RevocationEndpoint): + """The revocation endpoint for OAuth authorization servers allows clients + to notify the authorization server that a previously obtained refresh or + access token is no longer needed. + + Register it into authorization server, and create token endpoint response + for token revocation:: + + from django.views.decorators.http import require_http_methods + + # see register into authorization server instance + server.register_endpoint(RevocationEndpoint) + + @require_http_methods(["POST"]) + def revoke_token(request): + return server.create_endpoint_response( + RevocationEndpoint.ENDPOINT_NAME, + request + ) + """ + + def query_token(self, token, token_type_hint): + """Query requested token from database.""" + token_model = self.server.token_model + if token_type_hint == 'access_token': + rv = _query_access_token(token_model, token) + elif token_type_hint == 'refresh_token': + rv = _query_refresh_token(token_model, token) + else: + rv = _query_access_token(token_model, token) + if not rv: + rv = _query_refresh_token(token_model, token) + + return rv + + def revoke_token(self, token, request): + """Mark the give token as revoked.""" + token.revoked = True + token.save() + + +def _query_access_token(token_model, token): + try: + return token_model.objects.get(access_token=token) + except token_model.DoesNotExist: + return None + + +def _query_refresh_token(token_model, token): + try: + return token_model.objects.get(refresh_token=token) + except token_model.DoesNotExist: + return None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/requests.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/requests.py new file mode 100644 index 0000000000000000000000000000000000000000..e9f2d95a85aad561ea35ea04d8afb1d7b3cf7cc7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/requests.py @@ -0,0 +1,35 @@ +from django.http import HttpRequest +from django.utils.functional import cached_property +from authlib.common.encoding import json_loads +from authlib.oauth2.rfc6749 import OAuth2Request, JsonRequest + + +class DjangoOAuth2Request(OAuth2Request): + def __init__(self, request: HttpRequest): + super().__init__(request.method, request.build_absolute_uri(), None, request.headers) + self._request = request + + @property + def args(self): + return self._request.GET + + @property + def form(self): + return self._request.POST + + @cached_property + def data(self): + data = {} + data.update(self._request.GET.dict()) + data.update(self._request.POST.dict()) + return data + + +class DjangoJsonRequest(JsonRequest): + def __init__(self, request: HttpRequest): + super().__init__(request.method, request.build_absolute_uri(), None, request.headers) + self._request = request + + @cached_property + def data(self): + return json_loads(self._request.body) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/resource_protector.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/resource_protector.py new file mode 100644 index 0000000000000000000000000000000000000000..b89257babe03fc44b0872079292b133107a83273 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/resource_protector.py @@ -0,0 +1,75 @@ +import functools +from django.http import JsonResponse +from authlib.oauth2 import ( + OAuth2Error, + ResourceProtector as _ResourceProtector, +) +from authlib.oauth2.rfc6749 import ( + MissingAuthorizationError, +) +from authlib.oauth2.rfc6750 import ( + BearerTokenValidator as _BearerTokenValidator +) +from .requests import DjangoJsonRequest +from .signals import token_authenticated + + +class ResourceProtector(_ResourceProtector): + def acquire_token(self, request, scopes=None, **kwargs): + """A method to acquire current valid token with the given scope. + + :param request: Django HTTP request instance + :param scopes: a list of scope values + :return: token object + """ + req = DjangoJsonRequest(request) + # backward compatibility + kwargs['scopes'] = scopes + for claim in kwargs: + if isinstance(kwargs[claim], str): + kwargs[claim] = [kwargs[claim]] + token = self.validate_request(request=req, **kwargs) + token_authenticated.send(sender=self.__class__, token=token) + return token + + def __call__(self, scopes=None, optional=False, **kwargs): + claims = kwargs + # backward compatibility + claims['scopes'] = scopes + def wrapper(f): + @functools.wraps(f) + def decorated(request, *args, **kwargs): + try: + token = self.acquire_token(request, **claims) + request.oauth_token = token + except MissingAuthorizationError as error: + if optional: + request.oauth_token = None + return f(request, *args, **kwargs) + return return_error_response(error) + except OAuth2Error as error: + return return_error_response(error) + return f(request, *args, **kwargs) + return decorated + return wrapper + + +class BearerTokenValidator(_BearerTokenValidator): + def __init__(self, token_model, realm=None, **extra_attributes): + self.token_model = token_model + super().__init__(realm, **extra_attributes) + + def authenticate_token(self, token_string): + try: + return self.token_model.objects.get(access_token=token_string) + except self.token_model.DoesNotExist: + return None + + +def return_error_response(error): + body = dict(error.get_body()) + resp = JsonResponse(body, status=error.status_code) + headers = error.get_headers() + for k, v in headers: + resp[k] = v + return resp diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/signals.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/signals.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9c2659bddd421e7778393ddb3c32444c2c1cc6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/django_oauth2/signals.py @@ -0,0 +1,11 @@ +from django.dispatch import Signal + + +#: signal when client is authenticated +client_authenticated = Signal() + +#: signal when token is revoked +token_revoked = Signal() + +#: signal when token is authenticated +token_authenticated = Signal() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_client/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ecdca2df554fd2a27b811d78366b5d55d542e572 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_client/__init__.py @@ -0,0 +1,51 @@ +from werkzeug.local import LocalProxy +from .integration import FlaskIntegration, token_update +from .apps import FlaskOAuth1App, FlaskOAuth2App +from ..base_client import BaseOAuth, OAuthError + + +class OAuth(BaseOAuth): + oauth1_client_cls = FlaskOAuth1App + oauth2_client_cls = FlaskOAuth2App + framework_integration_cls = FlaskIntegration + + def __init__(self, app=None, cache=None, fetch_token=None, update_token=None): + super().__init__( + cache=cache, fetch_token=fetch_token, update_token=update_token) + self.app = app + if app: + self.init_app(app) + + def init_app(self, app, cache=None, fetch_token=None, update_token=None): + """Initialize lazy for Flask app. This is usually used for Flask application + factory pattern. + """ + self.app = app + if cache is not None: + self.cache = cache + + if fetch_token: + self.fetch_token = fetch_token + if update_token: + self.update_token = update_token + + app.extensions = getattr(app, 'extensions', {}) + app.extensions['authlib.integrations.flask_client'] = self + + def create_client(self, name): + if not self.app: + raise RuntimeError('OAuth is not init with Flask app.') + return super().create_client(name) + + def register(self, name, overwrite=False, **kwargs): + self._registry[name] = (overwrite, kwargs) + if self.app: + return self.create_client(name) + return LocalProxy(lambda: self.create_client(name)) + + +__all__ = [ + 'OAuth', 'FlaskIntegration', + 'FlaskOAuth1App', 'FlaskOAuth2App', + 'token_update', 'OAuthError', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_client/apps.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_client/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..7567f4b3b54a4bdca0ae9576a69a2d4365896ba9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_client/apps.py @@ -0,0 +1,107 @@ +from flask import g, redirect, request, session +from ..requests_client import OAuth1Session, OAuth2Session +from ..base_client import ( + BaseApp, OAuthError, + OAuth1Mixin, OAuth2Mixin, OpenIDMixin, +) + + +class FlaskAppMixin: + @property + def token(self): + attr = f'_oauth_token_{self.name}' + token = g.get(attr) + if token: + return token + if self._fetch_token: + token = self._fetch_token() + self.token = token + return token + + @token.setter + def token(self, token): + attr = f'_oauth_token_{self.name}' + setattr(g, attr, token) + + def _get_requested_token(self, *args, **kwargs): + return self.token + + def save_authorize_data(self, **kwargs): + state = kwargs.pop('state', None) + if state: + self.framework.set_state_data(session, state, kwargs) + else: + raise RuntimeError('Missing state value') + + def authorize_redirect(self, redirect_uri=None, **kwargs): + """Create a HTTP Redirect for Authorization Endpoint. + + :param redirect_uri: Callback or redirect URI for authorization. + :param kwargs: Extra parameters to include. + :return: A HTTP redirect response. + """ + rv = self.create_authorization_url(redirect_uri, **kwargs) + self.save_authorize_data(redirect_uri=redirect_uri, **rv) + return redirect(rv['url']) + + +class FlaskOAuth1App(FlaskAppMixin, OAuth1Mixin, BaseApp): + client_cls = OAuth1Session + + def authorize_access_token(self, **kwargs): + """Fetch access token in one step. + + :return: A token dict. + """ + params = request.args.to_dict(flat=True) + state = params.get('oauth_token') + if not state: + raise OAuthError(description='Missing "oauth_token" parameter') + + data = self.framework.get_state_data(session, state) + if not data: + raise OAuthError(description='Missing "request_token" in temporary data') + + params['request_token'] = data['request_token'] + params.update(kwargs) + self.framework.clear_state_data(session, state) + token = self.fetch_access_token(**params) + self.token = token + return token + + +class FlaskOAuth2App(FlaskAppMixin, OAuth2Mixin, OpenIDMixin, BaseApp): + client_cls = OAuth2Session + + def authorize_access_token(self, **kwargs): + """Fetch access token in one step. + + :return: A token dict. + """ + if request.method == 'GET': + error = request.args.get('error') + if error: + description = request.args.get('error_description') + raise OAuthError(error=error, description=description) + + params = { + 'code': request.args['code'], + 'state': request.args.get('state'), + } + else: + params = { + 'code': request.form['code'], + 'state': request.form.get('state'), + } + + claims_options = kwargs.pop('claims_options', None) + state_data = self.framework.get_state_data(session, params.get('state')) + self.framework.clear_state_data(session, params.get('state')) + params = self._format_state_params(state_data, params) + token = self.fetch_access_token(**params, **kwargs) + self.token = token + + if 'id_token' in token and 'nonce' in state_data: + userinfo = self.parse_id_token(token, nonce=state_data['nonce'], claims_options=claims_options) + token['userinfo'] = userinfo + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_client/integration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_client/integration.py new file mode 100644 index 0000000000000000000000000000000000000000..f4ea57e3f3696636224b4fd9283b12536b28043a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_client/integration.py @@ -0,0 +1,28 @@ +from flask import current_app +from flask.signals import Namespace +from ..base_client import FrameworkIntegration + +_signal = Namespace() +#: signal when token is updated +token_update = _signal.signal('token_update') + + +class FlaskIntegration(FrameworkIntegration): + def update_token(self, token, refresh_token=None, access_token=None): + token_update.send( + current_app, + name=self.name, + token=token, + refresh_token=refresh_token, + access_token=access_token, + ) + + @staticmethod + def load_config(oauth, name, params): + rv = {} + for k in params: + conf_key = f'{name}_{k}'.upper() + v = oauth.app.config.get(conf_key, None) + if v is not None: + rv[k] = v + return rv diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..780b059451f5ef4f597a6ad2763ab9baf58b91f3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/__init__.py @@ -0,0 +1,9 @@ +# flake8: noqa + +from .authorization_server import AuthorizationServer +from .resource_protector import ResourceProtector, current_credential +from .cache import ( + register_nonce_hooks, + register_temporary_credential_hooks, + create_exists_nonce_func, +) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/authorization_server.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/authorization_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3a2a5600769184e47b4be92446c275a673b61f8b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/authorization_server.py @@ -0,0 +1,182 @@ +import logging +from werkzeug.utils import import_string +from flask import Response +from flask import request as flask_req +from authlib.oauth1 import ( + OAuth1Request, + AuthorizationServer as _AuthorizationServer, +) +from authlib.common.security import generate_token +from authlib.common.urls import url_encode + +log = logging.getLogger(__name__) + + +class AuthorizationServer(_AuthorizationServer): + """Flask implementation of :class:`authlib.rfc5849.AuthorizationServer`. + Initialize it with Flask app instance, client model class and cache:: + + server = AuthorizationServer(app=app, query_client=query_client) + # or initialize lazily + server = AuthorizationServer() + server.init_app(app, query_client=query_client) + + :param app: A Flask app instance + :param query_client: A function to get client by client_id. The client + model class MUST implement the methods described by + :class:`~authlib.oauth1.rfc5849.ClientMixin`. + :param token_generator: A function to generate token + """ + + def __init__(self, app=None, query_client=None, token_generator=None): + self.app = app + self.query_client = query_client + self.token_generator = token_generator + + self._hooks = { + 'exists_nonce': None, + 'create_temporary_credential': None, + 'get_temporary_credential': None, + 'delete_temporary_credential': None, + 'create_authorization_verifier': None, + 'create_token_credential': None, + } + if app is not None: + self.init_app(app) + + def init_app(self, app, query_client=None, token_generator=None): + if query_client is not None: + self.query_client = query_client + if token_generator is not None: + self.token_generator = token_generator + + if self.token_generator is None: + self.token_generator = self.create_token_generator(app) + + methods = app.config.get('OAUTH1_SUPPORTED_SIGNATURE_METHODS') + if methods and isinstance(methods, (list, tuple)): + self.SUPPORTED_SIGNATURE_METHODS = methods + + self.app = app + + def register_hook(self, name, func): + if name not in self._hooks: + raise ValueError('Invalid "name" of hook') + self._hooks[name] = func + + def create_token_generator(self, app): + token_generator = app.config.get('OAUTH1_TOKEN_GENERATOR') + + if isinstance(token_generator, str): + token_generator = import_string(token_generator) + else: + length = app.config.get('OAUTH1_TOKEN_LENGTH', 42) + + def token_generator(): + return generate_token(length) + + secret_generator = app.config.get('OAUTH1_TOKEN_SECRET_GENERATOR') + if isinstance(secret_generator, str): + secret_generator = import_string(secret_generator) + else: + length = app.config.get('OAUTH1_TOKEN_SECRET_LENGTH', 48) + + def secret_generator(): + return generate_token(length) + + def create_token(): + return { + 'oauth_token': token_generator(), + 'oauth_token_secret': secret_generator() + } + return create_token + + def get_client_by_id(self, client_id): + return self.query_client(client_id) + + def exists_nonce(self, nonce, request): + func = self._hooks['exists_nonce'] + if callable(func): + timestamp = request.timestamp + client_id = request.client_id + token = request.token + return func(nonce, timestamp, client_id, token) + + raise RuntimeError('"exists_nonce" hook is required.') + + def create_temporary_credential(self, request): + func = self._hooks['create_temporary_credential'] + if callable(func): + token = self.token_generator() + return func(token, request.client_id, request.redirect_uri) + raise RuntimeError( + '"create_temporary_credential" hook is required.' + ) + + def get_temporary_credential(self, request): + func = self._hooks['get_temporary_credential'] + if callable(func): + return func(request.token) + + raise RuntimeError( + '"get_temporary_credential" hook is required.' + ) + + def delete_temporary_credential(self, request): + func = self._hooks['delete_temporary_credential'] + if callable(func): + return func(request.token) + + raise RuntimeError( + '"delete_temporary_credential" hook is required.' + ) + + def create_authorization_verifier(self, request): + func = self._hooks['create_authorization_verifier'] + if callable(func): + verifier = generate_token(36) + func(request.credential, request.user, verifier) + return verifier + + raise RuntimeError( + '"create_authorization_verifier" hook is required.' + ) + + def create_token_credential(self, request): + func = self._hooks['create_token_credential'] + if callable(func): + temporary_credential = request.credential + token = self.token_generator() + return func(token, temporary_credential) + + raise RuntimeError( + '"create_token_credential" hook is required.' + ) + + def check_authorization_request(self): + req = self.create_oauth1_request(None) + self.validate_authorization_request(req) + return req + + def create_authorization_response(self, request=None, grant_user=None): + return super()\ + .create_authorization_response(request, grant_user) + + def create_token_response(self, request=None): + return super().create_token_response(request) + + def create_oauth1_request(self, request): + if request is None: + request = flask_req + if request.method in ('POST', 'PUT'): + body = request.form.to_dict(flat=True) + else: + body = None + return OAuth1Request(request.method, request.url, body, request.headers) + + def handle_response(self, status_code, payload, headers): + return Response( + url_encode(payload), + status=status_code, + headers=headers + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/cache.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..fdfc9a5aa7a8a3a2d0c01992da403a1f04ea1c41 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/cache.py @@ -0,0 +1,80 @@ +from authlib.oauth1 import TemporaryCredential + + +def register_temporary_credential_hooks( + authorization_server, cache, key_prefix='temporary_credential:'): + """Register temporary credential related hooks to authorization server. + + :param authorization_server: AuthorizationServer instance + :param cache: Cache instance + :param key_prefix: key prefix for temporary credential + """ + + def create_temporary_credential(token, client_id, redirect_uri): + key = key_prefix + token['oauth_token'] + token['client_id'] = client_id + if redirect_uri: + token['oauth_callback'] = redirect_uri + + cache.set(key, token, timeout=86400) # cache for one day + return TemporaryCredential(token) + + def get_temporary_credential(oauth_token): + if not oauth_token: + return None + key = key_prefix + oauth_token + value = cache.get(key) + if value: + return TemporaryCredential(value) + + def delete_temporary_credential(oauth_token): + if oauth_token: + key = key_prefix + oauth_token + cache.delete(key) + + def create_authorization_verifier(credential, grant_user, verifier): + key = key_prefix + credential.get_oauth_token() + credential['oauth_verifier'] = verifier + credential['user_id'] = grant_user.get_user_id() + cache.set(key, credential, timeout=86400) + return credential + + authorization_server.register_hook( + 'create_temporary_credential', create_temporary_credential) + authorization_server.register_hook( + 'get_temporary_credential', get_temporary_credential) + authorization_server.register_hook( + 'delete_temporary_credential', delete_temporary_credential) + authorization_server.register_hook( + 'create_authorization_verifier', create_authorization_verifier) + + +def create_exists_nonce_func(cache, key_prefix='nonce:', expires=86400): + """Create an ``exists_nonce`` function that can be used in hooks and + resource protector. + + :param cache: Cache instance + :param key_prefix: key prefix for temporary credential + :param expires: Expire time for nonce + """ + def exists_nonce(nonce, timestamp, client_id, oauth_token): + key = f'{key_prefix}{nonce}-{timestamp}-{client_id}' + if oauth_token: + key = f'{key}-{oauth_token}' + rv = cache.has(key) + cache.set(key, 1, timeout=expires) + return rv + return exists_nonce + + +def register_nonce_hooks( + authorization_server, cache, key_prefix='nonce:', expires=86400): + """Register nonce related hooks to authorization server. + + :param authorization_server: AuthorizationServer instance + :param cache: Cache instance + :param key_prefix: key prefix for temporary credential + :param expires: Expire time for nonce + """ + exists_nonce = create_exists_nonce_func(cache, key_prefix, expires) + authorization_server.register_hook('exists_nonce', exists_nonce) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/resource_protector.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/resource_protector.py new file mode 100644 index 0000000000000000000000000000000000000000..c941eb422d40c7351365878a4c00c15676b106ed --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth1/resource_protector.py @@ -0,0 +1,113 @@ +import functools +from flask import g, json, Response +from flask import request as _req +from werkzeug.local import LocalProxy +from authlib.consts import default_json_headers +from authlib.oauth1 import ResourceProtector as _ResourceProtector +from authlib.oauth1.errors import OAuth1Error + + +class ResourceProtector(_ResourceProtector): + """A protecting method for resource servers. Initialize a resource + protector with the these method: + + 1. query_client + 2. query_token, + 3. exists_nonce + + Usually, a ``query_client`` method would look like (if using SQLAlchemy):: + + def query_client(client_id): + return Client.query.filter_by(client_id=client_id).first() + + A ``query_token`` method accept two parameters, ``client_id`` and ``oauth_token``:: + + def query_token(client_id, oauth_token): + return Token.query.filter_by(client_id=client_id, oauth_token=oauth_token).first() + + And for ``exists_nonce``, if using cache, we have a built-in hook to create this method:: + + from authlib.integrations.flask_oauth1 import create_exists_nonce_func + + exists_nonce = create_exists_nonce_func(cache) + + Then initialize the resource protector with those methods:: + + require_oauth = ResourceProtector( + app, query_client=query_client, + query_token=query_token, exists_nonce=exists_nonce, + ) + """ + def __init__(self, app=None, query_client=None, + query_token=None, exists_nonce=None): + self.query_client = query_client + self.query_token = query_token + self._exists_nonce = exists_nonce + + self.app = app + if app: + self.init_app(app) + + def init_app(self, app, query_client=None, query_token=None, + exists_nonce=None): + if query_client is not None: + self.query_client = query_client + if query_token is not None: + self.query_token = query_token + if exists_nonce is not None: + self._exists_nonce = exists_nonce + + methods = app.config.get('OAUTH1_SUPPORTED_SIGNATURE_METHODS') + if methods and isinstance(methods, (list, tuple)): + self.SUPPORTED_SIGNATURE_METHODS = methods + + self.app = app + + def get_client_by_id(self, client_id): + return self.query_client(client_id) + + def get_token_credential(self, request): + return self.query_token(request.client_id, request.token) + + def exists_nonce(self, nonce, request): + if not self._exists_nonce: + raise RuntimeError('"exists_nonce" function is required.') + + timestamp = request.timestamp + client_id = request.client_id + token = request.token + return self._exists_nonce(nonce, timestamp, client_id, token) + + def acquire_credential(self): + req = self.validate_request( + _req.method, + _req.url, + _req.form.to_dict(flat=True), + _req.headers + ) + g.authlib_server_oauth1_credential = req.credential + return req.credential + + def __call__(self, scope=None): + def wrapper(f): + @functools.wraps(f) + def decorated(*args, **kwargs): + try: + self.acquire_credential() + except OAuth1Error as error: + body = dict(error.get_body()) + return Response( + json.dumps(body), + status=error.status_code, + headers=default_json_headers, + ) + return f(*args, **kwargs) + return decorated + return wrapper + + +def _get_current_credential(): + return g.get('authlib_server_oauth1_credential') + + +current_credential = LocalProxy(_get_current_credential) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..170a7190a0e1f9d29e4c6881dd703b92e0cdce3b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/__init__.py @@ -0,0 +1,12 @@ +# flake8: noqa + +from .authorization_server import AuthorizationServer +from .resource_protector import ( + ResourceProtector, + current_token, +) +from .signals import ( + client_authenticated, + token_authenticated, + token_revoked, +) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/authorization_server.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/authorization_server.py new file mode 100644 index 0000000000000000000000000000000000000000..14510b277a639d49abc0af58cbd72bd70b09603e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/authorization_server.py @@ -0,0 +1,159 @@ +from werkzeug.utils import import_string +from flask import Response, json +from flask import request as flask_req +from authlib.oauth2 import ( + AuthorizationServer as _AuthorizationServer, +) +from authlib.oauth2.rfc6750 import BearerTokenGenerator +from authlib.common.security import generate_token +from .requests import FlaskOAuth2Request, FlaskJsonRequest +from .signals import client_authenticated, token_revoked + + +class AuthorizationServer(_AuthorizationServer): + """Flask implementation of :class:`authlib.oauth2.rfc6749.AuthorizationServer`. + Initialize it with ``query_client``, ``save_token`` methods and Flask + app instance:: + + def query_client(client_id): + return Client.query.filter_by(client_id=client_id).first() + + def save_token(token, request): + if request.user: + user_id = request.user.id + else: + user_id = None + client = request.client + tok = Token( + client_id=client.client_id, + user_id=user.id, + **token + ) + db.session.add(tok) + db.session.commit() + + server = AuthorizationServer(app, query_client, save_token) + # or initialize lazily + server = AuthorizationServer() + server.init_app(app, query_client, save_token) + """ + + def __init__(self, app=None, query_client=None, save_token=None): + super().__init__() + self._query_client = query_client + self._save_token = save_token + self._error_uris = None + if app is not None: + self.init_app(app) + + def init_app(self, app, query_client=None, save_token=None): + """Initialize later with Flask app instance.""" + if query_client is not None: + self._query_client = query_client + if save_token is not None: + self._save_token = save_token + + self.register_token_generator('default', self.create_bearer_token_generator(app.config)) + self.scopes_supported = app.config.get('OAUTH2_SCOPES_SUPPORTED') + self._error_uris = app.config.get('OAUTH2_ERROR_URIS') + + def query_client(self, client_id): + return self._query_client(client_id) + + def save_token(self, token, request): + return self._save_token(token, request) + + def get_error_uri(self, request, error): + if self._error_uris: + uris = dict(self._error_uris) + return uris.get(error.error) + + def create_oauth2_request(self, request): + return FlaskOAuth2Request(flask_req) + + def create_json_request(self, request): + return FlaskJsonRequest(flask_req) + + def handle_response(self, status_code, payload, headers): + if isinstance(payload, dict): + payload = json.dumps(payload) + return Response(payload, status=status_code, headers=headers) + + def send_signal(self, name, *args, **kwargs): + if name == 'after_authenticate_client': + client_authenticated.send(self, *args, **kwargs) + elif name == 'after_revoke_token': + token_revoked.send(self, *args, **kwargs) + + def create_bearer_token_generator(self, config): + """Create a generator function for generating ``token`` value. This + method will create a Bearer Token generator with + :class:`authlib.oauth2.rfc6750.BearerToken`. + + Configurable settings: + + 1. OAUTH2_ACCESS_TOKEN_GENERATOR: Boolean or import string, default is True. + 2. OAUTH2_REFRESH_TOKEN_GENERATOR: Boolean or import string, default is False. + 3. OAUTH2_TOKEN_EXPIRES_IN: Dict or import string, default is None. + + By default, it will not generate ``refresh_token``, which can be turn on by + configure ``OAUTH2_REFRESH_TOKEN_GENERATOR``. + + Here are some examples of the token generator:: + + OAUTH2_ACCESS_TOKEN_GENERATOR = 'your_project.generators.gen_token' + + # and in module `your_project.generators`, you can define: + + def gen_token(client, grant_type, user, scope): + # generate token according to these parameters + token = create_random_token() + return f'{client.id}-{user.id}-{token}' + + Here is an example of ``OAUTH2_TOKEN_EXPIRES_IN``:: + + OAUTH2_TOKEN_EXPIRES_IN = { + 'authorization_code': 864000, + 'urn:ietf:params:oauth:grant-type:jwt-bearer': 3600, + } + """ + conf = config.get('OAUTH2_ACCESS_TOKEN_GENERATOR', True) + access_token_generator = create_token_generator(conf, 42) + + conf = config.get('OAUTH2_REFRESH_TOKEN_GENERATOR', False) + refresh_token_generator = create_token_generator(conf, 48) + + expires_conf = config.get('OAUTH2_TOKEN_EXPIRES_IN') + expires_generator = create_token_expires_in_generator(expires_conf) + return BearerTokenGenerator( + access_token_generator, + refresh_token_generator, + expires_generator + ) + + +def create_token_expires_in_generator(expires_in_conf=None): + if isinstance(expires_in_conf, str): + return import_string(expires_in_conf) + + data = {} + data.update(BearerTokenGenerator.GRANT_TYPES_EXPIRES_IN) + if isinstance(expires_in_conf, dict): + data.update(expires_in_conf) + + def expires_in(client, grant_type): + return data.get(grant_type, BearerTokenGenerator.DEFAULT_EXPIRES_IN) + + return expires_in + + +def create_token_generator(token_generator_conf, length=42): + if callable(token_generator_conf): + return token_generator_conf + + if isinstance(token_generator_conf, str): + return import_string(token_generator_conf) + elif token_generator_conf is True: + def token_generator(*args, **kwargs): + return generate_token(length) + return token_generator diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/errors.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..fb2f3a1f0c133621724fff1f929c7216d6d769ce --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/errors.py @@ -0,0 +1,39 @@ +import importlib + +import werkzeug +from werkzeug.exceptions import HTTPException + +_version = importlib.metadata.version('werkzeug').split('.')[0] + +if _version in ('0', '1'): + class _HTTPException(HTTPException): + def __init__(self, code, body, headers, response=None): + super().__init__(None, response) + self.code = code + + self.body = body + self.headers = headers + + def get_body(self, environ=None): + return self.body + + def get_headers(self, environ=None): + return self.headers +else: + class _HTTPException(HTTPException): + def __init__(self, code, body, headers, response=None): + super().__init__(None, response) + self.code = code + + self.body = body + self.headers = headers + + def get_body(self, environ=None, scope=None): + return self.body + + def get_headers(self, environ=None, scope=None): + return self.headers + + +def raise_http_exception(status, body, headers): + raise _HTTPException(status, body, headers) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/requests.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/requests.py new file mode 100644 index 0000000000000000000000000000000000000000..0c2ab561e2716b367cb4a9df911840c12c74822e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/requests.py @@ -0,0 +1,30 @@ +from flask.wrappers import Request +from authlib.oauth2.rfc6749 import OAuth2Request, JsonRequest + + +class FlaskOAuth2Request(OAuth2Request): + def __init__(self, request: Request): + super().__init__(request.method, request.url, None, request.headers) + self._request = request + + @property + def args(self): + return self._request.args + + @property + def form(self): + return self._request.form + + @property + def data(self): + return self._request.values + + +class FlaskJsonRequest(JsonRequest): + def __init__(self, request: Request): + super().__init__(request.method, request.url, None, request.headers) + self._request = request + + @property + def data(self): + return self._request.get_json() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/resource_protector.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/resource_protector.py new file mode 100644 index 0000000000000000000000000000000000000000..be2b3fa24aefede21d7d4d5a5a72436abdf18c34 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/resource_protector.py @@ -0,0 +1,114 @@ +import functools +from contextlib import contextmanager +from flask import g, json +from flask import request as _req +from werkzeug.local import LocalProxy +from authlib.oauth2 import ( + OAuth2Error, + ResourceProtector as _ResourceProtector +) +from authlib.oauth2.rfc6749 import ( + MissingAuthorizationError, +) +from .requests import FlaskJsonRequest +from .signals import token_authenticated +from .errors import raise_http_exception + + +class ResourceProtector(_ResourceProtector): + """A protecting method for resource servers. Creating a ``require_oauth`` + decorator easily with ResourceProtector:: + + from authlib.integrations.flask_oauth2 import ResourceProtector + + require_oauth = ResourceProtector() + + # add bearer token validator + from authlib.oauth2.rfc6750 import BearerTokenValidator + from project.models import Token + + class MyBearerTokenValidator(BearerTokenValidator): + def authenticate_token(self, token_string): + return Token.query.filter_by(access_token=token_string).first() + + require_oauth.register_token_validator(MyBearerTokenValidator()) + + # protect resource with require_oauth + + @app.route('/user') + @require_oauth(['profile']) + def user_profile(): + user = User.get(current_token.user_id) + return jsonify(user.to_dict()) + + """ + def raise_error_response(self, error): + """Raise HTTPException for OAuth2Error. Developers can re-implement + this method to customize the error response. + + :param error: OAuth2Error + :raise: HTTPException + """ + status = error.status_code + body = json.dumps(dict(error.get_body())) + headers = error.get_headers() + raise_http_exception(status, body, headers) + + def acquire_token(self, scopes=None, **kwargs): + """A method to acquire current valid token with the given scope. + + :param scopes: a list of scope values + :return: token object + """ + request = FlaskJsonRequest(_req) + # backward compatibility + kwargs['scopes'] = scopes + for claim in kwargs: + if isinstance(kwargs[claim], str): + kwargs[claim] = [kwargs[claim]] + token = self.validate_request(request=request, **kwargs) + token_authenticated.send(self, token=token) + g.authlib_server_oauth2_token = token + return token + + @contextmanager + def acquire(self, scopes=None): + """The with statement of ``require_oauth``. Instead of using a + decorator, you can use a with statement instead:: + + @app.route('/api/user') + def user_api(): + with require_oauth.acquire('profile') as token: + user = User.get(token.user_id) + return jsonify(user.to_dict()) + """ + try: + yield self.acquire_token(scopes) + except OAuth2Error as error: + self.raise_error_response(error) + + def __call__(self, scopes=None, optional=False, **kwargs): + claims = kwargs + # backward compatibility + claims['scopes'] = scopes + def wrapper(f): + @functools.wraps(f) + def decorated(*args, **kwargs): + try: + self.acquire_token(**claims) + except MissingAuthorizationError as error: + if optional: + return f(*args, **kwargs) + self.raise_error_response(error) + except OAuth2Error as error: + self.raise_error_response(error) + return f(*args, **kwargs) + return decorated + return wrapper + + +def _get_current_token(): + return g.get('authlib_server_oauth2_token') + + +current_token = LocalProxy(_get_current_token) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/signals.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/signals.py new file mode 100644 index 0000000000000000000000000000000000000000..c61e0119df03a68c52190b5112544be65c2adb0f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/flask_oauth2/signals.py @@ -0,0 +1,12 @@ +from flask.signals import Namespace + +_signal = Namespace() + +#: signal when client is authenticated +client_authenticated = _signal.signal('client_authenticated') + +#: signal when token is revoked +token_revoked = _signal.signal('token_revoked') + +#: signal when token is authenticated +token_authenticated = _signal.signal('token_authenticated') diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3b5437ccb4d21b78decbbcc57973b4c790e250f9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/__init__.py @@ -0,0 +1,25 @@ +from authlib.oauth1 import ( + SIGNATURE_HMAC_SHA1, + SIGNATURE_RSA_SHA1, + SIGNATURE_PLAINTEXT, + SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY, + SIGNATURE_TYPE_BODY, +) +from .oauth1_client import OAuth1Auth, AsyncOAuth1Client, OAuth1Client +from .oauth2_client import ( + OAuth2Auth, OAuth2Client, OAuth2ClientAuth, + AsyncOAuth2Client, +) +from .assertion_client import AssertionClient, AsyncAssertionClient +from ..base_client import OAuthError + + +__all__ = [ + 'OAuthError', + 'OAuth1Auth', 'AsyncOAuth1Client', + 'SIGNATURE_HMAC_SHA1', 'SIGNATURE_RSA_SHA1', 'SIGNATURE_PLAINTEXT', + 'SIGNATURE_TYPE_HEADER', 'SIGNATURE_TYPE_QUERY', 'SIGNATURE_TYPE_BODY', + 'OAuth2Auth', 'OAuth2ClientAuth', 'OAuth2Client', 'AsyncOAuth2Client', + 'AssertionClient', 'AsyncAssertionClient', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/assertion_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/assertion_client.py new file mode 100644 index 0000000000000000000000000000000000000000..83dc58b29f8a4c30cd58a74ebf9cff2f61a38ab0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/assertion_client.py @@ -0,0 +1,81 @@ +import httpx +from httpx import Response, USE_CLIENT_DEFAULT +from authlib.oauth2.rfc7521 import AssertionClient as _AssertionClient +from authlib.oauth2.rfc7523 import JWTBearerGrant +from .utils import extract_client_kwargs +from .oauth2_client import OAuth2Auth +from ..base_client import OAuthError + +__all__ = ['AsyncAssertionClient'] + + +class AsyncAssertionClient(_AssertionClient, httpx.AsyncClient): + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError + JWT_BEARER_GRANT_TYPE = JWTBearerGrant.GRANT_TYPE + ASSERTION_METHODS = { + JWT_BEARER_GRANT_TYPE: JWTBearerGrant.sign, + } + DEFAULT_GRANT_TYPE = JWT_BEARER_GRANT_TYPE + + def __init__(self, token_endpoint, issuer, subject, audience=None, grant_type=None, + claims=None, token_placement='header', scope=None, **kwargs): + + client_kwargs = extract_client_kwargs(kwargs) + httpx.AsyncClient.__init__(self, **client_kwargs) + + _AssertionClient.__init__( + self, session=None, + token_endpoint=token_endpoint, issuer=issuer, subject=subject, + audience=audience, grant_type=grant_type, claims=claims, + token_placement=token_placement, scope=scope, **kwargs + ) + + async def request(self, method, url, withhold_token=False, auth=USE_CLIENT_DEFAULT, **kwargs) -> Response: + """Send request with auto refresh token feature.""" + if not withhold_token and auth is USE_CLIENT_DEFAULT: + if not self.token or self.token.is_expired(): + await self.refresh_token() + + auth = self.token_auth + return await super().request( + method, url, auth=auth, **kwargs) + + async def _refresh_token(self, data): + resp = await self.request( + 'POST', self.token_endpoint, data=data, withhold_token=True) + + return self.parse_response_token(resp) + + +class AssertionClient(_AssertionClient, httpx.Client): + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError + JWT_BEARER_GRANT_TYPE = JWTBearerGrant.GRANT_TYPE + ASSERTION_METHODS = { + JWT_BEARER_GRANT_TYPE: JWTBearerGrant.sign, + } + DEFAULT_GRANT_TYPE = JWT_BEARER_GRANT_TYPE + + def __init__(self, token_endpoint, issuer, subject, audience=None, grant_type=None, + claims=None, token_placement='header', scope=None, **kwargs): + + client_kwargs = extract_client_kwargs(kwargs) + httpx.Client.__init__(self, **client_kwargs) + + _AssertionClient.__init__( + self, session=self, + token_endpoint=token_endpoint, issuer=issuer, subject=subject, + audience=audience, grant_type=grant_type, claims=claims, + token_placement=token_placement, scope=scope, **kwargs + ) + + def request(self, method, url, withhold_token=False, auth=USE_CLIENT_DEFAULT, **kwargs): + """Send request with auto refresh token feature.""" + if not withhold_token and auth is USE_CLIENT_DEFAULT: + if not self.token or self.token.is_expired(): + self.refresh_token() + + auth = self.token_auth + return super().request( + method, url, auth=auth, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/oauth1_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/oauth1_client.py new file mode 100644 index 0000000000000000000000000000000000000000..ce031c97d63c461cb3850bd3658e2b3989a0f029 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/oauth1_client.py @@ -0,0 +1,102 @@ +import typing +import httpx +from httpx import Auth, Request, Response +from authlib.oauth1 import ( + SIGNATURE_HMAC_SHA1, + SIGNATURE_TYPE_HEADER, +) +from authlib.common.encoding import to_unicode +from authlib.oauth1 import ClientAuth +from authlib.oauth1.client import OAuth1Client as _OAuth1Client +from .utils import build_request, extract_client_kwargs +from ..base_client import OAuthError + + +class OAuth1Auth(Auth, ClientAuth): + """Signs the httpx request using OAuth 1 (RFC5849)""" + requires_request_body = True + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + url, headers, body = self.prepare( + request.method, str(request.url), request.headers, request.content) + headers['Content-Length'] = str(len(body)) + yield build_request(url=url, headers=headers, body=body, initial_request=request) + + +class AsyncOAuth1Client(_OAuth1Client, httpx.AsyncClient): + auth_class = OAuth1Auth + + def __init__(self, client_id, client_secret=None, + token=None, token_secret=None, + redirect_uri=None, rsa_key=None, verifier=None, + signature_method=SIGNATURE_HMAC_SHA1, + signature_type=SIGNATURE_TYPE_HEADER, + force_include_body=False, **kwargs): + + _client_kwargs = extract_client_kwargs(kwargs) + httpx.AsyncClient.__init__(self, **_client_kwargs) + + _OAuth1Client.__init__( + self, None, + client_id=client_id, client_secret=client_secret, + token=token, token_secret=token_secret, + redirect_uri=redirect_uri, rsa_key=rsa_key, verifier=verifier, + signature_method=signature_method, signature_type=signature_type, + force_include_body=force_include_body, **kwargs) + + async def fetch_access_token(self, url, verifier=None, **kwargs): + """Method for fetching an access token from the token endpoint. + + This is the final step in the OAuth 1 workflow. An access token is + obtained using all previously obtained credentials, including the + verifier from the authorization step. + + :param url: Access Token endpoint. + :param verifier: A verifier string to prove authorization was granted. + :param kwargs: Extra parameters to include for fetching access token. + :return: A token dict. + """ + if verifier: + self.auth.verifier = verifier + if not self.auth.verifier: + self.handle_error('missing_verifier', 'Missing "verifier" value') + token = await self._fetch_token(url, **kwargs) + self.auth.verifier = None + return token + + async def _fetch_token(self, url, **kwargs): + resp = await self.post(url, **kwargs) + text = await resp.aread() + token = self.parse_response_token(resp.status_code, to_unicode(text)) + self.token = token + return token + + @staticmethod + def handle_error(error_type, error_description): + raise OAuthError(error_type, error_description) + + +class OAuth1Client(_OAuth1Client, httpx.Client): + auth_class = OAuth1Auth + + def __init__(self, client_id, client_secret=None, + token=None, token_secret=None, + redirect_uri=None, rsa_key=None, verifier=None, + signature_method=SIGNATURE_HMAC_SHA1, + signature_type=SIGNATURE_TYPE_HEADER, + force_include_body=False, **kwargs): + + _client_kwargs = extract_client_kwargs(kwargs) + httpx.Client.__init__(self, **_client_kwargs) + + _OAuth1Client.__init__( + self, self, + client_id=client_id, client_secret=client_secret, + token=token, token_secret=token_secret, + redirect_uri=redirect_uri, rsa_key=rsa_key, verifier=verifier, + signature_method=signature_method, signature_type=signature_type, + force_include_body=force_include_body, **kwargs) + + @staticmethod + def handle_error(error_type, error_description): + raise OAuthError(error_type, error_description) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/oauth2_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/oauth2_client.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ee0f584d1f52c5f2c48550d0cfcd97e6737487 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/oauth2_client.py @@ -0,0 +1,220 @@ +import typing +from contextlib import asynccontextmanager + +import httpx +from httpx import Auth, Request, Response, USE_CLIENT_DEFAULT +from anyio import Lock # Import after httpx so import errors refer to httpx +from authlib.common.urls import url_decode +from authlib.oauth2.client import OAuth2Client as _OAuth2Client +from authlib.oauth2.auth import ClientAuth, TokenAuth +from .utils import HTTPX_CLIENT_KWARGS, build_request +from ..base_client import ( + OAuthError, + InvalidTokenError, + MissingTokenError, + UnsupportedTokenTypeError, +) + +__all__ = [ + 'OAuth2Auth', 'OAuth2ClientAuth', + 'AsyncOAuth2Client', 'OAuth2Client', +] + + +class OAuth2Auth(Auth, TokenAuth): + """Sign requests for OAuth 2.0, currently only bearer token is supported.""" + requires_request_body = True + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + try: + url, headers, body = self.prepare( + str(request.url), request.headers, request.content) + headers['Content-Length'] = str(len(body)) + yield build_request(url=url, headers=headers, body=body, initial_request=request) + except KeyError as error: + description = f'Unsupported token_type: {str(error)}' + raise UnsupportedTokenTypeError(description=description) + + +class OAuth2ClientAuth(Auth, ClientAuth): + requires_request_body = True + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + url, headers, body = self.prepare( + request.method, str(request.url), request.headers, request.content) + headers['Content-Length'] = str(len(body)) + yield build_request(url=url, headers=headers, body=body, initial_request=request) + + +class AsyncOAuth2Client(_OAuth2Client, httpx.AsyncClient): + SESSION_REQUEST_PARAMS = HTTPX_CLIENT_KWARGS + + client_auth_class = OAuth2ClientAuth + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError + + def __init__(self, client_id=None, client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, redirect_uri=None, + token=None, token_placement='header', + update_token=None, **kwargs): + + # extract httpx.Client kwargs + client_kwargs = self._extract_session_request_params(kwargs) + httpx.AsyncClient.__init__(self, **client_kwargs) + + # We use a Lock to synchronize coroutines to prevent + # multiple concurrent attempts to refresh the same token + self._token_refresh_lock = Lock() + + _OAuth2Client.__init__( + self, session=None, + client_id=client_id, client_secret=client_secret, + token_endpoint_auth_method=token_endpoint_auth_method, + revocation_endpoint_auth_method=revocation_endpoint_auth_method, + scope=scope, redirect_uri=redirect_uri, + token=token, token_placement=token_placement, + update_token=update_token, **kwargs + ) + + async def request(self, method, url, withhold_token=False, auth=USE_CLIENT_DEFAULT, **kwargs): + if not withhold_token and auth is USE_CLIENT_DEFAULT: + if not self.token: + raise MissingTokenError() + + await self.ensure_active_token(self.token) + + auth = self.token_auth + + return await super().request( + method, url, auth=auth, **kwargs) + + @asynccontextmanager + async def stream(self, method, url, withhold_token=False, auth=USE_CLIENT_DEFAULT, **kwargs): + if not withhold_token and auth is USE_CLIENT_DEFAULT: + if not self.token: + raise MissingTokenError() + + await self.ensure_active_token(self.token) + + auth = self.token_auth + + async with super().stream( + method, url, auth=auth, **kwargs) as resp: + yield resp + + async def ensure_active_token(self, token): + async with self._token_refresh_lock: + if self.token.is_expired(): + refresh_token = token.get('refresh_token') + url = self.metadata.get('token_endpoint') + if refresh_token and url: + await self.refresh_token(url, refresh_token=refresh_token) + elif self.metadata.get('grant_type') == 'client_credentials': + access_token = token['access_token'] + new_token = await self.fetch_token(url, grant_type='client_credentials') + if self.update_token: + await self.update_token(new_token, access_token=access_token) + else: + raise InvalidTokenError() + + async def _fetch_token(self, url, body='', headers=None, auth=USE_CLIENT_DEFAULT, + method='POST', **kwargs): + if method.upper() == 'POST': + resp = await self.post( + url, data=dict(url_decode(body)), headers=headers, + auth=auth, **kwargs) + else: + if '?' in url: + url = '&'.join([url, body]) + else: + url = '?'.join([url, body]) + resp = await self.get(url, headers=headers, auth=auth, **kwargs) + + for hook in self.compliance_hook['access_token_response']: + resp = hook(resp) + + return self.parse_response_token(resp) + + async def _refresh_token(self, url, refresh_token=None, body='', + headers=None, auth=USE_CLIENT_DEFAULT, **kwargs): + resp = await self.post( + url, data=dict(url_decode(body)), headers=headers, + auth=auth, **kwargs) + + for hook in self.compliance_hook['refresh_token_response']: + resp = hook(resp) + + token = self.parse_response_token(resp) + if 'refresh_token' not in token: + self.token['refresh_token'] = refresh_token + + if self.update_token: + await self.update_token(self.token, refresh_token=refresh_token) + + return self.token + + def _http_post(self, url, body=None, auth=USE_CLIENT_DEFAULT, headers=None, **kwargs): + return self.post( + url, data=dict(url_decode(body)), + headers=headers, auth=auth, **kwargs) + + +class OAuth2Client(_OAuth2Client, httpx.Client): + SESSION_REQUEST_PARAMS = HTTPX_CLIENT_KWARGS + + client_auth_class = OAuth2ClientAuth + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError + + def __init__(self, client_id=None, client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, redirect_uri=None, + token=None, token_placement='header', + update_token=None, **kwargs): + + # extract httpx.Client kwargs + client_kwargs = self._extract_session_request_params(kwargs) + httpx.Client.__init__(self, **client_kwargs) + + _OAuth2Client.__init__( + self, session=self, + client_id=client_id, client_secret=client_secret, + token_endpoint_auth_method=token_endpoint_auth_method, + revocation_endpoint_auth_method=revocation_endpoint_auth_method, + scope=scope, redirect_uri=redirect_uri, + token=token, token_placement=token_placement, + update_token=update_token, **kwargs + ) + + @staticmethod + def handle_error(error_type, error_description): + raise OAuthError(error_type, error_description) + + def request(self, method, url, withhold_token=False, auth=USE_CLIENT_DEFAULT, **kwargs): + if not withhold_token and auth is USE_CLIENT_DEFAULT: + if not self.token: + raise MissingTokenError() + + if not self.ensure_active_token(self.token): + raise InvalidTokenError() + + auth = self.token_auth + + return super().request( + method, url, auth=auth, **kwargs) + + def stream(self, method, url, withhold_token=False, auth=USE_CLIENT_DEFAULT, **kwargs): + if not withhold_token and auth is USE_CLIENT_DEFAULT: + if not self.token: + raise MissingTokenError() + + if not self.ensure_active_token(self.token): + raise InvalidTokenError() + + auth = self.token_auth + + return super().stream( + method, url, auth=auth, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/utils.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8f19f37b7520ceffbd6b4d0d8e1588a86ac4b43c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/httpx_client/utils.py @@ -0,0 +1,30 @@ +from httpx import Request + +HTTPX_CLIENT_KWARGS = [ + 'headers', 'cookies', 'verify', 'cert', 'http1', 'http2', + 'proxies', 'timeout', 'follow_redirects', 'limits', 'max_redirects', + 'event_hooks', 'base_url', 'transport', 'app', 'trust_env', +] + + +def extract_client_kwargs(kwargs): + client_kwargs = {} + for k in HTTPX_CLIENT_KWARGS: + if k in kwargs: + client_kwargs[k] = kwargs.pop(k) + return client_kwargs + + +def build_request(url, headers, body, initial_request: Request) -> Request: + """Make sure that all the data from initial request is passed to the updated object""" + updated_request = Request( + method=initial_request.method, + url=url, + headers=headers, + content=body + ) + + if hasattr(initial_request, 'extensions'): + updated_request.extensions = initial_request.extensions + + return updated_request diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fcbdec32024a4e5ea870144dc38dbd4560594356 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/__init__.py @@ -0,0 +1,22 @@ +from .oauth1_session import OAuth1Session, OAuth1Auth +from .oauth2_session import OAuth2Session, OAuth2Auth +from .assertion_session import AssertionSession +from ..base_client import OAuthError +from authlib.oauth1 import ( + SIGNATURE_HMAC_SHA1, + SIGNATURE_RSA_SHA1, + SIGNATURE_PLAINTEXT, + SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY, + SIGNATURE_TYPE_BODY, +) + + +__all__ = [ + 'OAuthError', + 'OAuth1Session', 'OAuth1Auth', + 'SIGNATURE_HMAC_SHA1', 'SIGNATURE_RSA_SHA1', 'SIGNATURE_PLAINTEXT', + 'SIGNATURE_TYPE_HEADER', 'SIGNATURE_TYPE_QUERY', 'SIGNATURE_TYPE_BODY', + 'OAuth2Session', 'OAuth2Auth', + 'AssertionSession', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/assertion_session.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/assertion_session.py new file mode 100644 index 0000000000000000000000000000000000000000..d07c00160689435f3367775997cf822cfb9e2aad --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/assertion_session.py @@ -0,0 +1,46 @@ +from requests import Session +from authlib.oauth2.rfc7521 import AssertionClient +from authlib.oauth2.rfc7523 import JWTBearerGrant +from .oauth2_session import OAuth2Auth +from .utils import update_session_configure + + +class AssertionAuth(OAuth2Auth): + def ensure_active_token(self): + if not self.token or self.token.is_expired() and self.client: + return self.client.refresh_token() + + +class AssertionSession(AssertionClient, Session): + """Constructs a new Assertion Framework for OAuth 2.0 Authorization Grants + per RFC7521_. + + .. _RFC7521: https://tools.ietf.org/html/rfc7521 + """ + token_auth_class = AssertionAuth + JWT_BEARER_GRANT_TYPE = JWTBearerGrant.GRANT_TYPE + ASSERTION_METHODS = { + JWT_BEARER_GRANT_TYPE: JWTBearerGrant.sign, + } + DEFAULT_GRANT_TYPE = JWT_BEARER_GRANT_TYPE + + def __init__(self, token_endpoint, issuer, subject, audience=None, grant_type=None, + claims=None, token_placement='header', scope=None, default_timeout=None, **kwargs): + Session.__init__(self) + self.default_timeout = default_timeout + update_session_configure(self, kwargs) + AssertionClient.__init__( + self, session=self, + token_endpoint=token_endpoint, issuer=issuer, subject=subject, + audience=audience, grant_type=grant_type, claims=claims, + token_placement=token_placement, scope=scope, **kwargs + ) + + def request(self, method, url, withhold_token=False, auth=None, **kwargs): + """Send request with auto refresh token feature.""" + if self.default_timeout: + kwargs.setdefault('timeout', self.default_timeout) + if not withhold_token and auth is None: + auth = self.token_auth + return super().request( + method, url, auth=auth, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/oauth1_session.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/oauth1_session.py new file mode 100644 index 0000000000000000000000000000000000000000..8c49fa983bc0a24d454a076134c6702392cc4db0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/oauth1_session.py @@ -0,0 +1,59 @@ +from requests import Session +from requests.auth import AuthBase +from authlib.oauth1 import ( + SIGNATURE_HMAC_SHA1, + SIGNATURE_TYPE_HEADER, +) +from authlib.common.encoding import to_native +from authlib.oauth1 import ClientAuth +from authlib.oauth1.client import OAuth1Client +from ..base_client import OAuthError +from .utils import update_session_configure + + +class OAuth1Auth(AuthBase, ClientAuth): + """Signs the request using OAuth 1 (RFC5849)""" + + def __call__(self, req): + url, headers, body = self.prepare( + req.method, req.url, req.headers, req.body) + + req.url = to_native(url) + req.prepare_headers(headers) + if body: + req.body = body + return req + + +class OAuth1Session(OAuth1Client, Session): + auth_class = OAuth1Auth + + def __init__(self, client_id, client_secret=None, + token=None, token_secret=None, + redirect_uri=None, rsa_key=None, verifier=None, + signature_method=SIGNATURE_HMAC_SHA1, + signature_type=SIGNATURE_TYPE_HEADER, + force_include_body=False, **kwargs): + Session.__init__(self) + update_session_configure(self, kwargs) + OAuth1Client.__init__( + self, session=self, + client_id=client_id, client_secret=client_secret, + token=token, token_secret=token_secret, + redirect_uri=redirect_uri, rsa_key=rsa_key, verifier=verifier, + signature_method=signature_method, signature_type=signature_type, + force_include_body=force_include_body, **kwargs) + + def rebuild_auth(self, prepared_request, response): + """When being redirected we should always strip Authorization + header, since nonce may not be reused as per OAuth spec. + """ + if 'Authorization' in prepared_request.headers: + # If we get redirected to a new host, we should strip out + # any authentication headers. + prepared_request.headers.pop('Authorization', True) + prepared_request.prepare_auth(self.auth) + + @staticmethod + def handle_error(error_type, error_description): + raise OAuthError(error_type, error_description) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/oauth2_session.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/oauth2_session.py new file mode 100644 index 0000000000000000000000000000000000000000..9e2426a24052eb635b70574b23e522402456e826 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/oauth2_session.py @@ -0,0 +1,110 @@ +from requests import Session +from requests.auth import AuthBase +from authlib.oauth2.client import OAuth2Client +from authlib.oauth2.auth import ClientAuth, TokenAuth +from ..base_client import ( + OAuthError, + InvalidTokenError, + MissingTokenError, + UnsupportedTokenTypeError, +) +from .utils import update_session_configure + +__all__ = ['OAuth2Session', 'OAuth2Auth'] + + +class OAuth2Auth(AuthBase, TokenAuth): + """Sign requests for OAuth 2.0, currently only bearer token is supported.""" + + def ensure_active_token(self): + if self.client and not self.client.ensure_active_token(self.token): + raise InvalidTokenError() + + def __call__(self, req): + self.ensure_active_token() + try: + req.url, req.headers, req.body = self.prepare( + req.url, req.headers, req.body) + except KeyError as error: + description = f'Unsupported token_type: {str(error)}' + raise UnsupportedTokenTypeError(description=description) + return req + + +class OAuth2ClientAuth(AuthBase, ClientAuth): + """Attaches OAuth Client Authentication to the given Request object. + """ + def __call__(self, req): + req.url, req.headers, req.body = self.prepare( + req.method, req.url, req.headers, req.body + ) + return req + + +class OAuth2Session(OAuth2Client, Session): + """Construct a new OAuth 2 client requests session. + + :param client_id: Client ID, which you get from client registration. + :param client_secret: Client Secret, which you get from registration. + :param authorization_endpoint: URL of the authorization server's + authorization endpoint. + :param token_endpoint: URL of the authorization server's token endpoint. + :param token_endpoint_auth_method: client authentication method for + token endpoint. + :param revocation_endpoint: URL of the authorization server's OAuth 2.0 + revocation endpoint. + :param revocation_endpoint_auth_method: client authentication method for + revocation endpoint. + :param scope: Scope that you needed to access user resources. + :param state: Shared secret to prevent CSRF attack. + :param redirect_uri: Redirect URI you registered as callback. + :param token: A dict of token attributes such as ``access_token``, + ``token_type`` and ``expires_at``. + :param token_placement: The place to put token in HTTP request. Available + values: "header", "body", "uri". + :param update_token: A function for you to update token. It accept a + :class:`OAuth2Token` as parameter. + :param default_timeout: If settled, every requests will have a default timeout. + """ + client_auth_class = OAuth2ClientAuth + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError + SESSION_REQUEST_PARAMS = ( + 'allow_redirects', 'timeout', 'cookies', 'files', + 'proxies', 'hooks', 'stream', 'verify', 'cert', 'json' + ) + + def __init__(self, client_id=None, client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, state=None, redirect_uri=None, + token=None, token_placement='header', + update_token=None, default_timeout=None, **kwargs): + Session.__init__(self) + self.default_timeout = default_timeout + update_session_configure(self, kwargs) + + OAuth2Client.__init__( + self, session=self, + client_id=client_id, client_secret=client_secret, + token_endpoint_auth_method=token_endpoint_auth_method, + revocation_endpoint_auth_method=revocation_endpoint_auth_method, + scope=scope, state=state, redirect_uri=redirect_uri, + token=token, token_placement=token_placement, + update_token=update_token, **kwargs + ) + + def fetch_access_token(self, url=None, **kwargs): + """Alias for fetch_token.""" + return self.fetch_token(url, **kwargs) + + def request(self, method, url, withhold_token=False, auth=None, **kwargs): + """Send request with auto refresh token feature (if available).""" + if self.default_timeout: + kwargs.setdefault('timeout', self.default_timeout) + if not withhold_token and auth is None: + if not self.token: + raise MissingTokenError() + auth = self.token_auth + return super().request( + method, url, auth=auth, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/utils.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..53a07db3200502eb099282ad8616809b52f7e908 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/requests_client/utils.py @@ -0,0 +1,10 @@ +REQUESTS_SESSION_KWARGS = [ + 'proxies', 'hooks', 'stream', 'verify', 'cert', + 'max_redirects', 'trust_env', +] + + +def update_session_configure(session, kwargs): + for k in REQUESTS_SESSION_KWARGS: + if k in kwargs: + setattr(session, k, kwargs.pop(k)) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1964aa1a571aed6dc46574cbc4f8afe787a9519c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/__init__.py @@ -0,0 +1,17 @@ +from .client_mixin import OAuth2ClientMixin +from .tokens_mixins import OAuth2AuthorizationCodeMixin, OAuth2TokenMixin +from .functions import ( + create_query_client_func, + create_save_token_func, + create_query_token_func, + create_revocation_endpoint, + create_bearer_token_validator, +) + + +__all__ = [ + 'OAuth2ClientMixin', 'OAuth2AuthorizationCodeMixin', 'OAuth2TokenMixin', + 'create_query_client_func', 'create_save_token_func', + 'create_query_token_func', 'create_revocation_endpoint', + 'create_bearer_token_validator', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/client_mixin.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/client_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..28505cda68e6a558256df7a63649bc1f296d96b3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/client_mixin.py @@ -0,0 +1,138 @@ +import secrets + +from sqlalchemy import Column, String, Text, Integer +from authlib.common.encoding import json_loads, json_dumps +from authlib.oauth2.rfc6749 import ClientMixin +from authlib.oauth2.rfc6749 import scope_to_list, list_to_scope + + +class OAuth2ClientMixin(ClientMixin): + client_id = Column(String(48), index=True) + client_secret = Column(String(120)) + client_id_issued_at = Column(Integer, nullable=False, default=0) + client_secret_expires_at = Column(Integer, nullable=False, default=0) + _client_metadata = Column('client_metadata', Text) + + @property + def client_info(self): + """Implementation for Client Info in OAuth 2.0 Dynamic Client + Registration Protocol via `Section 3.2.1`_. + + .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc7591#section-3.2.1 + """ + return dict( + client_id=self.client_id, + client_secret=self.client_secret, + client_id_issued_at=self.client_id_issued_at, + client_secret_expires_at=self.client_secret_expires_at, + ) + + @property + def client_metadata(self): + if 'client_metadata' in self.__dict__: + return self.__dict__['client_metadata'] + if self._client_metadata: + data = json_loads(self._client_metadata) + self.__dict__['client_metadata'] = data + return data + return {} + + def set_client_metadata(self, value): + self._client_metadata = json_dumps(value) + if 'client_metadata' in self.__dict__: + del self.__dict__['client_metadata'] + + @property + def redirect_uris(self): + return self.client_metadata.get('redirect_uris', []) + + @property + def token_endpoint_auth_method(self): + return self.client_metadata.get( + 'token_endpoint_auth_method', + 'client_secret_basic' + ) + + @property + def grant_types(self): + return self.client_metadata.get('grant_types', []) + + @property + def response_types(self): + return self.client_metadata.get('response_types', []) + + @property + def client_name(self): + return self.client_metadata.get('client_name') + + @property + def client_uri(self): + return self.client_metadata.get('client_uri') + + @property + def logo_uri(self): + return self.client_metadata.get('logo_uri') + + @property + def scope(self): + return self.client_metadata.get('scope', '') + + @property + def contacts(self): + return self.client_metadata.get('contacts', []) + + @property + def tos_uri(self): + return self.client_metadata.get('tos_uri') + + @property + def policy_uri(self): + return self.client_metadata.get('policy_uri') + + @property + def jwks_uri(self): + return self.client_metadata.get('jwks_uri') + + @property + def jwks(self): + return self.client_metadata.get('jwks', []) + + @property + def software_id(self): + return self.client_metadata.get('software_id') + + @property + def software_version(self): + return self.client_metadata.get('software_version') + + def get_client_id(self): + return self.client_id + + def get_default_redirect_uri(self): + if self.redirect_uris: + return self.redirect_uris[0] + + def get_allowed_scope(self, scope): + if not scope: + return '' + allowed = set(self.scope.split()) + scopes = scope_to_list(scope) + return list_to_scope([s for s in scopes if s in allowed]) + + def check_redirect_uri(self, redirect_uri): + return redirect_uri in self.redirect_uris + + def check_client_secret(self, client_secret): + return secrets.compare_digest(self.client_secret, client_secret) + + def check_endpoint_auth_method(self, method, endpoint): + if endpoint == 'token': + return self.token_endpoint_auth_method == method + # TODO + return True + + def check_response_type(self, response_type): + return response_type in self.response_types + + def check_grant_type(self, grant_type): + return grant_type in self.grant_types diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/functions.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..74f10712aa9bf2f5ed6b8dc82c458b80450b07e8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/functions.py @@ -0,0 +1,101 @@ +import time + + +def create_query_client_func(session, client_model): + """Create an ``query_client`` function that can be used in authorization + server. + + :param session: SQLAlchemy session + :param client_model: Client model class + """ + def query_client(client_id): + q = session.query(client_model) + return q.filter_by(client_id=client_id).first() + return query_client + + +def create_save_token_func(session, token_model): + """Create an ``save_token`` function that can be used in authorization + server. + + :param session: SQLAlchemy session + :param token_model: Token model class + """ + def save_token(token, request): + if request.user: + user_id = request.user.get_user_id() + else: + user_id = None + client = request.client + item = token_model( + client_id=client.client_id, + user_id=user_id, + **token + ) + session.add(item) + session.commit() + return save_token + + +def create_query_token_func(session, token_model): + """Create an ``query_token`` function for revocation, introspection + token endpoints. + + :param session: SQLAlchemy session + :param token_model: Token model class + """ + def query_token(token, token_type_hint): + q = session.query(token_model) + if token_type_hint == 'access_token': + return q.filter_by(access_token=token).first() + elif token_type_hint == 'refresh_token': + return q.filter_by(refresh_token=token).first() + # without token_type_hint + item = q.filter_by(access_token=token).first() + if item: + return item + return q.filter_by(refresh_token=token).first() + return query_token + + +def create_revocation_endpoint(session, token_model): + """Create a revocation endpoint class with SQLAlchemy session + and token model. + + :param session: SQLAlchemy session + :param token_model: Token model class + """ + from authlib.oauth2.rfc7009 import RevocationEndpoint + query_token = create_query_token_func(session, token_model) + + class _RevocationEndpoint(RevocationEndpoint): + def query_token(self, token, token_type_hint): + return query_token(token, token_type_hint) + + def revoke_token(self, token, request): + now = int(time.time()) + hint = request.form.get('token_type_hint') + token.access_token_revoked_at = now + if hint != 'access_token': + token.refresh_token_revoked_at = now + session.add(token) + session.commit() + + return _RevocationEndpoint + + +def create_bearer_token_validator(session, token_model): + """Create an bearer token validator class with SQLAlchemy session + and token model. + + :param session: SQLAlchemy session + :param token_model: Token model class + """ + from authlib.oauth2.rfc6750 import BearerTokenValidator + + class _BearerTokenValidator(BearerTokenValidator): + def authenticate_token(self, token_string): + q = session.query(token_model) + return q.filter_by(access_token=token_string).first() + + return _BearerTokenValidator diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/tokens_mixins.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/tokens_mixins.py new file mode 100644 index 0000000000000000000000000000000000000000..28cee8922add69c8a1e05e987209694839015d06 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/sqla_oauth2/tokens_mixins.py @@ -0,0 +1,70 @@ +import time +from sqlalchemy import Column, String, Text, Integer +from authlib.oauth2.rfc6749 import ( + TokenMixin, + AuthorizationCodeMixin, +) + + +class OAuth2AuthorizationCodeMixin(AuthorizationCodeMixin): + code = Column(String(120), unique=True, nullable=False) + client_id = Column(String(48)) + redirect_uri = Column(Text, default='') + response_type = Column(Text, default='') + scope = Column(Text, default='') + nonce = Column(Text) + auth_time = Column( + Integer, nullable=False, + default=lambda: int(time.time()) + ) + + code_challenge = Column(Text) + code_challenge_method = Column(String(48)) + + def is_expired(self): + return self.auth_time + 300 < time.time() + + def get_redirect_uri(self): + return self.redirect_uri + + def get_scope(self): + return self.scope + + def get_auth_time(self): + return self.auth_time + + def get_nonce(self): + return self.nonce + + +class OAuth2TokenMixin(TokenMixin): + client_id = Column(String(48)) + token_type = Column(String(40)) + access_token = Column(String(255), unique=True, nullable=False) + refresh_token = Column(String(255), index=True) + scope = Column(Text, default='') + issued_at = Column( + Integer, nullable=False, default=lambda: int(time.time()) + ) + access_token_revoked_at = Column(Integer, nullable=False, default=0) + refresh_token_revoked_at = Column(Integer, nullable=False, default=0) + expires_in = Column(Integer, nullable=False, default=0) + + def check_client(self, client): + return self.client_id == client.get_client_id() + + def get_scope(self): + return self.scope + + def get_expires_in(self): + return self.expires_in + + def is_revoked(self): + return self.access_token_revoked_at or self.refresh_token_revoked_at + + def is_expired(self): + if not self.expires_in: + return False + + expires_at = self.issued_at + self.expires_in + return expires_at < time.time() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/starlette_client/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/starlette_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7546c5471fc8c32943077f0df90106da53252583 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/starlette_client/__init__.py @@ -0,0 +1,22 @@ +# flake8: noqa + +from ..base_client import BaseOAuth, OAuthError +from .integration import StarletteIntegration +from .apps import StarletteOAuth1App, StarletteOAuth2App + + +class OAuth(BaseOAuth): + oauth1_client_cls = StarletteOAuth1App + oauth2_client_cls = StarletteOAuth2App + framework_integration_cls = StarletteIntegration + + def __init__(self, config=None, cache=None, fetch_token=None, update_token=None): + super().__init__( + cache=cache, fetch_token=fetch_token, update_token=update_token) + self.config = config + + +__all__ = [ + 'OAuth', 'OAuthError', + 'StarletteIntegration', 'StarletteOAuth1App', 'StarletteOAuth2App', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/starlette_client/apps.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/starlette_client/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..114cbaff5beeedbbe86aaeb4691575fa591c38b8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/starlette_client/apps.py @@ -0,0 +1,86 @@ +from starlette.datastructures import URL +from starlette.responses import RedirectResponse +from ..base_client import OAuthError +from ..base_client import BaseApp +from ..base_client.async_app import AsyncOAuth1Mixin, AsyncOAuth2Mixin +from ..base_client.async_openid import AsyncOpenIDMixin +from ..httpx_client import AsyncOAuth1Client, AsyncOAuth2Client + + +class StarletteAppMixin: + async def save_authorize_data(self, request, **kwargs): + state = kwargs.pop('state', None) + if state: + if self.framework.cache: + session = None + else: + session = request.session + await self.framework.set_state_data(session, state, kwargs) + else: + raise RuntimeError('Missing state value') + + async def authorize_redirect(self, request, redirect_uri=None, **kwargs): + """Create a HTTP Redirect for Authorization Endpoint. + + :param request: HTTP request instance from Starlette view. + :param redirect_uri: Callback or redirect URI for authorization. + :param kwargs: Extra parameters to include. + :return: A HTTP redirect response. + """ + + # Handle Starlette >= 0.26.0 where redirect_uri may now be a URL and not a string + if redirect_uri and isinstance(redirect_uri, URL): + redirect_uri = str(redirect_uri) + rv = await self.create_authorization_url(redirect_uri, **kwargs) + await self.save_authorize_data(request, redirect_uri=redirect_uri, **rv) + return RedirectResponse(rv['url'], status_code=302) + + +class StarletteOAuth1App(StarletteAppMixin, AsyncOAuth1Mixin, BaseApp): + client_cls = AsyncOAuth1Client + + async def authorize_access_token(self, request, **kwargs): + params = dict(request.query_params) + state = params.get('oauth_token') + if not state: + raise OAuthError(description='Missing "oauth_token" parameter') + + data = await self.framework.get_state_data(request.session, state) + if not data: + raise OAuthError(description='Missing "request_token" in temporary data') + + params['request_token'] = data['request_token'] + params.update(kwargs) + await self.framework.clear_state_data(request.session, state) + return await self.fetch_access_token(**params) + + +class StarletteOAuth2App(StarletteAppMixin, AsyncOAuth2Mixin, AsyncOpenIDMixin, BaseApp): + client_cls = AsyncOAuth2Client + + async def authorize_access_token(self, request, **kwargs): + error = request.query_params.get('error') + if error: + description = request.query_params.get('error_description') + raise OAuthError(error=error, description=description) + + params = { + 'code': request.query_params.get('code'), + 'state': request.query_params.get('state'), + } + + if self.framework.cache: + session = None + else: + session = request.session + + claims_options = kwargs.pop('claims_options', None) + state_data = await self.framework.get_state_data(session, params.get('state')) + await self.framework.clear_state_data(session, params.get('state')) + params = self._format_state_params(state_data, params) + token = await self.fetch_access_token(**params, **kwargs) + + if 'id_token' in token and 'nonce' in state_data: + userinfo = await self.parse_id_token(token, nonce=state_data['nonce'], claims_options=claims_options) + token['userinfo'] = userinfo + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/starlette_client/integration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/starlette_client/integration.py new file mode 100644 index 0000000000000000000000000000000000000000..04ffd78699dc4e32d0273363c0825a8aae4e7554 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/integrations/starlette_client/integration.py @@ -0,0 +1,66 @@ +import json +import time +from typing import ( + Any, + Dict, + Hashable, + Optional, +) + +from ..base_client import FrameworkIntegration + + +class StarletteIntegration(FrameworkIntegration): + async def _get_cache_data(self, key: Hashable): + value = await self.cache.get(key) + if not value: + return None + try: + return json.loads(value) + except (TypeError, ValueError): + return None + + async def get_state_data(self, session: Optional[Dict[str, Any]], state: str) -> Dict[str, Any]: + key = f'_state_{self.name}_{state}' + if self.cache: + value = await self._get_cache_data(key) + elif session is not None: + value = session.get(key) + else: + value = None + + if value: + return value.get('data') + return None + + async def set_state_data(self, session: Optional[Dict[str, Any]], state: str, data: Any): + key = f'_state_{self.name}_{state}' + if self.cache: + await self.cache.set(key, json.dumps({'data': data}), self.expires_in) + elif session is not None: + now = time.time() + session[key] = {'data': data, 'exp': now + self.expires_in} + + async def clear_state_data(self, session: Optional[Dict[str, Any]], state: str): + key = f'_state_{self.name}_{state}' + if self.cache: + await self.cache.delete(key) + elif session is not None: + session.pop(key, None) + self._clear_session_state(session) + + def update_token(self, token, refresh_token=None, access_token=None): + pass + + @staticmethod + def load_config(oauth, name, params): + if not oauth.config: + return {} + + rv = {} + for k in params: + conf_key = f'{name}_{k}'.upper() + v = oauth.config.get(conf_key, default=None) + if v is not None: + rv[k] = v + return rv diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2d6638a096a6a05eff08d03d4a04544b5c9a73d8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/__init__.py @@ -0,0 +1,60 @@ +""" + authlib.jose + ~~~~~~~~~~~~ + + JOSE implementation in Authlib. Tracking the status of JOSE specs at + https://tools.ietf.org/wg/jose/ +""" +from .rfc7515 import ( + JsonWebSignature, JWSAlgorithm, JWSHeader, JWSObject, +) +from .rfc7516 import ( + JsonWebEncryption, JWEAlgorithm, JWEEncAlgorithm, JWEZipAlgorithm, +) +from .rfc7517 import Key, KeySet, JsonWebKey +from .rfc7518 import ( + register_jws_rfc7518, + register_jwe_rfc7518, + ECDHESAlgorithm, + OctKey, + RSAKey, + ECKey, +) +from .rfc7519 import JsonWebToken, BaseClaims, JWTClaims +from .rfc8037 import OKPKey, register_jws_rfc8037 + +from .errors import JoseError + +# register algorithms +register_jws_rfc7518(JsonWebSignature) +register_jws_rfc8037(JsonWebSignature) + +register_jwe_rfc7518(JsonWebEncryption) + +# attach algorithms +ECDHESAlgorithm.ALLOWED_KEY_CLS = (ECKey, OKPKey) + +# register supported keys +JsonWebKey.JWK_KEY_CLS = { + OctKey.kty: OctKey, + RSAKey.kty: RSAKey, + ECKey.kty: ECKey, + OKPKey.kty: OKPKey, +} + +jwt = JsonWebToken(list(JsonWebSignature.ALGORITHMS_REGISTRY.keys())) + + +__all__ = [ + 'JoseError', + + 'JsonWebSignature', 'JWSAlgorithm', 'JWSHeader', 'JWSObject', + 'JsonWebEncryption', 'JWEAlgorithm', 'JWEEncAlgorithm', 'JWEZipAlgorithm', + + 'JsonWebKey', 'Key', 'KeySet', + + 'OctKey', 'RSAKey', 'ECKey', 'OKPKey', + + 'JsonWebToken', 'BaseClaims', 'JWTClaims', + 'jwt', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3044585e106537373b68dd0bad5033d568f6ab71 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/__init__.py @@ -0,0 +1,17 @@ +from ._jwe_algorithms import JWE_DRAFT_ALG_ALGORITHMS +from ._jwe_enc_cryptography import C20PEncAlgorithm +try: + from ._jwe_enc_cryptodome import XC20PEncAlgorithm +except ImportError: + XC20PEncAlgorithm = None + + +def register_jwe_draft(cls): + for alg in JWE_DRAFT_ALG_ALGORITHMS: + cls.register_algorithm(alg) + + cls.register_algorithm(C20PEncAlgorithm(256)) # C20P + if XC20PEncAlgorithm is not None: + cls.register_algorithm(XC20PEncAlgorithm(256)) # XC20P + +__all__ = ['register_jwe_draft'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/_jwe_algorithms.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/_jwe_algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..c01b7e7d3d9dc662eeca7f6f1f3e90f41de0a87f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/_jwe_algorithms.py @@ -0,0 +1,188 @@ +import struct +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHash + +from authlib.jose.errors import InvalidEncryptionAlgorithmForECDH1PUWithKeyWrappingError +from authlib.jose.rfc7516 import JWEAlgorithmWithTagAwareKeyAgreement +from authlib.jose.rfc7518 import AESAlgorithm, CBCHS2EncAlgorithm, ECKey, u32be_len_input +from authlib.jose.rfc8037 import OKPKey + + +class ECDH1PUAlgorithm(JWEAlgorithmWithTagAwareKeyAgreement): + EXTRA_HEADERS = ['epk', 'apu', 'apv', 'skid'] + ALLOWED_KEY_CLS = (ECKey, OKPKey) + + # https://datatracker.ietf.org/doc/html/draft-madden-jose-ecdh-1pu-04 + def __init__(self, key_size=None): + if key_size is None: + self.name = 'ECDH-1PU' + self.description = 'ECDH-1PU in the Direct Key Agreement mode' + else: + self.name = f'ECDH-1PU+A{key_size}KW' + self.description = ( + 'ECDH-1PU using Concat KDF and CEK wrapped ' + 'with A{}KW').format(key_size) + self.key_size = key_size + self.aeskw = AESAlgorithm(key_size) + + def prepare_key(self, raw_data): + if isinstance(raw_data, self.ALLOWED_KEY_CLS): + return raw_data + return ECKey.import_key(raw_data) + + def generate_preset(self, enc_alg, key): + epk = self._generate_ephemeral_key(key) + h = self._prepare_headers(epk) + preset = {'epk': epk, 'header': h} + if self.key_size is not None: + cek = enc_alg.generate_cek() + preset['cek'] = cek + return preset + + def compute_shared_key(self, shared_key_e, shared_key_s): + return shared_key_e + shared_key_s + + def compute_fixed_info(self, headers, bit_size, tag): + if tag is None: + cctag = b'' + else: + cctag = u32be_len_input(tag) + + # AlgorithmID + if self.key_size is None: + alg_id = u32be_len_input(headers['enc']) + else: + alg_id = u32be_len_input(headers['alg']) + + # PartyUInfo + apu_info = u32be_len_input(headers.get('apu'), True) + + # PartyVInfo + apv_info = u32be_len_input(headers.get('apv'), True) + + # SuppPubInfo + pub_info = struct.pack('>I', bit_size) + cctag + + return alg_id + apu_info + apv_info + pub_info + + def compute_derived_key(self, shared_key, fixed_info, bit_size): + ckdf = ConcatKDFHash( + algorithm=hashes.SHA256(), + length=bit_size // 8, + otherinfo=fixed_info, + backend=default_backend() + ) + return ckdf.derive(shared_key) + + def deliver_at_sender(self, sender_static_key, sender_ephemeral_key, recipient_pubkey, headers, bit_size, tag): + shared_key_s = sender_static_key.exchange_shared_key(recipient_pubkey) + shared_key_e = sender_ephemeral_key.exchange_shared_key(recipient_pubkey) + shared_key = self.compute_shared_key(shared_key_e, shared_key_s) + + fixed_info = self.compute_fixed_info(headers, bit_size, tag) + + return self.compute_derived_key(shared_key, fixed_info, bit_size) + + def deliver_at_recipient(self, recipient_key, sender_static_pubkey, sender_ephemeral_pubkey, headers, bit_size, tag): + shared_key_s = recipient_key.exchange_shared_key(sender_static_pubkey) + shared_key_e = recipient_key.exchange_shared_key(sender_ephemeral_pubkey) + shared_key = self.compute_shared_key(shared_key_e, shared_key_s) + + fixed_info = self.compute_fixed_info(headers, bit_size, tag) + + return self.compute_derived_key(shared_key, fixed_info, bit_size) + + def _generate_ephemeral_key(self, key): + return key.generate_key(key['crv'], is_private=True) + + def _prepare_headers(self, epk): + # REQUIRED_JSON_FIELDS contains only public fields + pub_epk = {k: epk[k] for k in epk.REQUIRED_JSON_FIELDS} + pub_epk['kty'] = epk.kty + return {'epk': pub_epk} + + def generate_keys_and_prepare_headers(self, enc_alg, key, sender_key, preset=None): + if not isinstance(enc_alg, CBCHS2EncAlgorithm): + raise InvalidEncryptionAlgorithmForECDH1PUWithKeyWrappingError() + + if preset and 'epk' in preset: + epk = preset['epk'] + h = {} + else: + epk = self._generate_ephemeral_key(key) + h = self._prepare_headers(epk) + + if preset and 'cek' in preset: + cek = preset['cek'] + else: + cek = enc_alg.generate_cek() + + return {'epk': epk, 'cek': cek, 'header': h} + + def _agree_upon_key_at_sender(self, enc_alg, headers, key, sender_key, epk, tag=None): + if self.key_size is None: + bit_size = enc_alg.CEK_SIZE + else: + bit_size = self.key_size + + public_key = key.get_op_key('wrapKey') + + return self.deliver_at_sender(sender_key, epk, public_key, headers, bit_size, tag) + + def _wrap_cek(self, cek, dk): + kek = self.aeskw.prepare_key(dk) + return self.aeskw.wrap_cek(cek, kek) + + def agree_upon_key_and_wrap_cek(self, enc_alg, headers, key, sender_key, epk, cek, tag): + dk = self._agree_upon_key_at_sender(enc_alg, headers, key, sender_key, epk, tag) + return self._wrap_cek(cek, dk) + + def wrap(self, enc_alg, headers, key, sender_key, preset=None): + # In this class this method is used in direct key agreement mode only + if self.key_size is not None: + raise RuntimeError('Invalid algorithm state detected') + + if preset and 'epk' in preset: + epk = preset['epk'] + h = {} + else: + epk = self._generate_ephemeral_key(key) + h = self._prepare_headers(epk) + + dk = self._agree_upon_key_at_sender(enc_alg, headers, key, sender_key, epk) + + return {'ek': b'', 'cek': dk, 'header': h} + + def unwrap(self, enc_alg, ek, headers, key, sender_key, tag=None): + if 'epk' not in headers: + raise ValueError('Missing "epk" in headers') + + if self.key_size is None: + bit_size = enc_alg.CEK_SIZE + else: + bit_size = self.key_size + + sender_pubkey = sender_key.get_op_key('wrapKey') + epk = key.import_key(headers['epk']) + epk_pubkey = epk.get_op_key('wrapKey') + dk = self.deliver_at_recipient(key, sender_pubkey, epk_pubkey, headers, bit_size, tag) + + if self.key_size is None: + return dk + + kek = self.aeskw.prepare_key(dk) + return self.aeskw.unwrap(enc_alg, ek, headers, kek) + + +JWE_DRAFT_ALG_ALGORITHMS = [ + ECDH1PUAlgorithm(None), # ECDH-1PU + ECDH1PUAlgorithm(128), # ECDH-1PU+A128KW + ECDH1PUAlgorithm(192), # ECDH-1PU+A192KW + ECDH1PUAlgorithm(256), # ECDH-1PU+A256KW +] + + +def register_jwe_alg_draft(cls): + for alg in JWE_DRAFT_ALG_ALGORITHMS: + cls.register_algorithm(alg) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/_jwe_enc_cryptodome.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/_jwe_enc_cryptodome.py new file mode 100644 index 0000000000000000000000000000000000000000..cb6fceaff62de7c7f37f8b400f47abf8fc39502f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/_jwe_enc_cryptodome.py @@ -0,0 +1,52 @@ +""" + authlib.jose.draft + ~~~~~~~~~~~~~~~~~~~~ + + Content Encryption per `Section 4`_. + + .. _`Section 4`: https://datatracker.ietf.org/doc/html/draft-amringer-jose-chacha-02#section-4 +""" +from authlib.jose.rfc7516 import JWEEncAlgorithm +from Cryptodome.Cipher import ChaCha20_Poly1305 as Cryptodome_ChaCha20_Poly1305 + + +class XC20PEncAlgorithm(JWEEncAlgorithm): + # Use of an IV of size 192 bits is REQUIRED with this algorithm. + # https://datatracker.ietf.org/doc/html/draft-amringer-jose-chacha-02#section-4.1 + IV_SIZE = 192 + + def __init__(self, key_size): + self.name = 'XC20P' + self.description = 'XChaCha20-Poly1305' + self.key_size = key_size + self.CEK_SIZE = key_size + + def encrypt(self, msg, aad, iv, key): + """Content Encryption with AEAD_XCHACHA20_POLY1305 + + :param msg: text to be encrypt in bytes + :param aad: additional authenticated data in bytes + :param iv: initialization vector in bytes + :param key: encrypted key in bytes + :return: (ciphertext, tag) + """ + self.check_iv(iv) + chacha = Cryptodome_ChaCha20_Poly1305.new(key=key, nonce=iv) + chacha.update(aad) + ciphertext, tag = chacha.encrypt_and_digest(msg) + return ciphertext, tag + + def decrypt(self, ciphertext, aad, iv, tag, key): + """Content Decryption with AEAD_XCHACHA20_POLY1305 + + :param ciphertext: ciphertext in bytes + :param aad: additional authenticated data in bytes + :param iv: initialization vector in bytes + :param tag: authentication tag in bytes + :param key: encrypted key in bytes + :return: message + """ + self.check_iv(iv) + chacha = Cryptodome_ChaCha20_Poly1305.new(key=key, nonce=iv) + chacha.update(aad) + return chacha.decrypt_and_verify(ciphertext, tag) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/_jwe_enc_cryptography.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/_jwe_enc_cryptography.py new file mode 100644 index 0000000000000000000000000000000000000000..1b0c852b9067f643f219c1ac95878b171d1f7a9e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/drafts/_jwe_enc_cryptography.py @@ -0,0 +1,50 @@ +""" + authlib.jose.draft + ~~~~~~~~~~~~~~~~~~~~ + + Content Encryption per `Section 4`_. + + .. _`Section 4`: https://datatracker.ietf.org/doc/html/draft-amringer-jose-chacha-02#section-4 +""" +from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 +from authlib.jose.rfc7516 import JWEEncAlgorithm + + +class C20PEncAlgorithm(JWEEncAlgorithm): + # Use of an IV of size 96 bits is REQUIRED with this algorithm. + # https://datatracker.ietf.org/doc/html/draft-amringer-jose-chacha-02#section-4.1 + IV_SIZE = 96 + + def __init__(self, key_size): + self.name = 'C20P' + self.description = 'ChaCha20-Poly1305' + self.key_size = key_size + self.CEK_SIZE = key_size + + def encrypt(self, msg, aad, iv, key): + """Content Encryption with AEAD_CHACHA20_POLY1305 + + :param msg: text to be encrypt in bytes + :param aad: additional authenticated data in bytes + :param iv: initialization vector in bytes + :param key: encrypted key in bytes + :return: (ciphertext, tag) + """ + self.check_iv(iv) + chacha = ChaCha20Poly1305(key) + ciphertext = chacha.encrypt(iv, msg, aad) + return ciphertext[:-16], ciphertext[-16:] + + def decrypt(self, ciphertext, aad, iv, tag, key): + """Content Decryption with AEAD_CHACHA20_POLY1305 + + :param ciphertext: ciphertext in bytes + :param aad: additional authenticated data in bytes + :param iv: initialization vector in bytes + :param tag: authentication tag in bytes + :param key: encrypted key in bytes + :return: message + """ + self.check_iv(iv) + chacha = ChaCha20Poly1305(key) + return chacha.decrypt(iv, ciphertext + tag, aad) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/errors.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..fb02eb4e868309eb2d5f0c819e36599f40b32d7f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/errors.py @@ -0,0 +1,113 @@ +from authlib.common.errors import AuthlibBaseError + + +class JoseError(AuthlibBaseError): + pass + + +class DecodeError(JoseError): + error = 'decode_error' + + +class MissingAlgorithmError(JoseError): + error = 'missing_algorithm' + + +class UnsupportedAlgorithmError(JoseError): + error = 'unsupported_algorithm' + + +class BadSignatureError(JoseError): + error = 'bad_signature' + + def __init__(self, result): + super().__init__() + self.result = result + + +class InvalidHeaderParameterNameError(JoseError): + error = 'invalid_header_parameter_name' + + def __init__(self, name): + description = f'Invalid Header Parameter Name: {name}' + super().__init__( + description=description) + + +class InvalidEncryptionAlgorithmForECDH1PUWithKeyWrappingError(JoseError): + error = 'invalid_encryption_algorithm_for_ECDH_1PU_with_key_wrapping' + + def __init__(self): + description = 'In key agreement with key wrapping mode ECDH-1PU algorithm ' \ + 'only supports AES_CBC_HMAC_SHA2 family encryption algorithms' + super().__init__( + description=description) + + +class InvalidAlgorithmForMultipleRecipientsMode(JoseError): + error = 'invalid_algorithm_for_multiple_recipients_mode' + + def __init__(self, alg): + description = f'{alg} algorithm cannot be used in multiple recipients mode' + super().__init__( + description=description) + + +class KeyMismatchError(JoseError): + error = 'key_mismatch_error' + description = 'Key does not match to any recipient' + + +class MissingEncryptionAlgorithmError(JoseError): + error = 'missing_encryption_algorithm' + description = 'Missing "enc" in header' + + +class UnsupportedEncryptionAlgorithmError(JoseError): + error = 'unsupported_encryption_algorithm' + description = 'Unsupported "enc" value in header' + + +class UnsupportedCompressionAlgorithmError(JoseError): + error = 'unsupported_compression_algorithm' + description = 'Unsupported "zip" value in header' + + +class InvalidUseError(JoseError): + error = 'invalid_use' + description = 'Key "use" is not valid for your usage' + + +class InvalidClaimError(JoseError): + error = 'invalid_claim' + + def __init__(self, claim): + self.claim_name = claim + description = f'Invalid claim "{claim}"' + super().__init__(description=description) + + +class MissingClaimError(JoseError): + error = 'missing_claim' + + def __init__(self, claim): + description = f'Missing "{claim}" claim' + super().__init__(description=description) + + +class InsecureClaimError(JoseError): + error = 'insecure_claim' + + def __init__(self, claim): + description = f'Insecure claim "{claim}"' + super().__init__(description=description) + + +class ExpiredTokenError(JoseError): + error = 'expired_token' + description = 'The token is expired' + + +class InvalidTokenError(JoseError): + error = 'invalid_token' + description = 'The token is not valid yet' diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/jwk.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/jwk.py new file mode 100644 index 0000000000000000000000000000000000000000..bc3b6eb5ba8f9e17d4a704ad5ef429b925d66bac --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/jwk.py @@ -0,0 +1,19 @@ +from authlib.deprecate import deprecate +from .rfc7517 import JsonWebKey + + +def loads(obj, kid=None): + deprecate('Please use ``JsonWebKey`` directly.') + key_set = JsonWebKey.import_key_set(obj) + if key_set: + return key_set.find_by_kid(kid) + return JsonWebKey.import_key(obj) + + +def dumps(key, kty=None, **params): + deprecate('Please use ``JsonWebKey`` directly.') + if kty: + params['kty'] = kty + + key = JsonWebKey.import_key(key, params) + return dict(key) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7515/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7515/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f8e0f5f59cb336c89f2b8cf4047a222371be4f9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7515/__init__.py @@ -0,0 +1,18 @@ +""" + authlib.jose.rfc7515 + ~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + JSON Web Signature (JWS). + + https://tools.ietf.org/html/rfc7515 +""" + +from .jws import JsonWebSignature +from .models import JWSAlgorithm, JWSHeader, JWSObject + + +__all__ = [ + 'JsonWebSignature', + 'JWSAlgorithm', 'JWSHeader', 'JWSObject' +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7515/jws.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7515/jws.py new file mode 100644 index 0000000000000000000000000000000000000000..cf19c4ba7c316057de1d02d201cef610a8bdaf10 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7515/jws.py @@ -0,0 +1,304 @@ +from authlib.common.encoding import ( + to_bytes, + to_unicode, + urlsafe_b64encode, + json_b64encode, +) +from authlib.jose.util import ( + extract_header, + extract_segment, ensure_dict, +) +from authlib.jose.errors import ( + DecodeError, + MissingAlgorithmError, + UnsupportedAlgorithmError, + BadSignatureError, + InvalidHeaderParameterNameError, +) +from .models import JWSHeader, JWSObject + + +class JsonWebSignature: + + #: Registered Header Parameter Names defined by Section 4.1 + REGISTERED_HEADER_PARAMETER_NAMES = frozenset([ + 'alg', 'jku', 'jwk', 'kid', + 'x5u', 'x5c', 'x5t', 'x5t#S256', + 'typ', 'cty', 'crit' + ]) + + #: Defined available JWS algorithms in the registry + ALGORITHMS_REGISTRY = {} + + def __init__(self, algorithms=None, private_headers=None): + self._private_headers = private_headers + self._algorithms = algorithms + + @classmethod + def register_algorithm(cls, algorithm): + if not algorithm or algorithm.algorithm_type != 'JWS': + raise ValueError( + f'Invalid algorithm for JWS, {algorithm!r}') + cls.ALGORITHMS_REGISTRY[algorithm.name] = algorithm + + def serialize_compact(self, protected, payload, key): + """Generate a JWS Compact Serialization. The JWS Compact Serialization + represents digitally signed or MACed content as a compact, URL-safe + string, per `Section 7.1`_. + + .. code-block:: text + + BASE64URL(UTF8(JWS Protected Header)) || '.' || + BASE64URL(JWS Payload) || '.' || + BASE64URL(JWS Signature) + + :param protected: A dict of protected header + :param payload: A bytes/string of payload + :param key: Private key used to generate signature + :return: byte + """ + jws_header = JWSHeader(protected, None) + self._validate_private_headers(protected) + algorithm, key = self._prepare_algorithm_key(protected, payload, key) + + protected_segment = json_b64encode(jws_header.protected) + payload_segment = urlsafe_b64encode(to_bytes(payload)) + + # calculate signature + signing_input = b'.'.join([protected_segment, payload_segment]) + signature = urlsafe_b64encode(algorithm.sign(signing_input, key)) + return b'.'.join([protected_segment, payload_segment, signature]) + + def deserialize_compact(self, s, key, decode=None): + """Exact JWS Compact Serialization, and validate with the given key. + If key is not provided, the returned dict will contain the signature, + and signing input values. Via `Section 7.1`_. + + :param s: text of JWS Compact Serialization + :param key: key used to verify the signature + :param decode: a function to decode payload data + :return: JWSObject + :raise: BadSignatureError + + .. _`Section 7.1`: https://tools.ietf.org/html/rfc7515#section-7.1 + """ + try: + s = to_bytes(s) + signing_input, signature_segment = s.rsplit(b'.', 1) + protected_segment, payload_segment = signing_input.split(b'.', 1) + except ValueError: + raise DecodeError('Not enough segments') + + protected = _extract_header(protected_segment) + jws_header = JWSHeader(protected, None) + + payload = _extract_payload(payload_segment) + if decode: + payload = decode(payload) + + signature = _extract_signature(signature_segment) + rv = JWSObject(jws_header, payload, 'compact') + algorithm, key = self._prepare_algorithm_key(jws_header, payload, key) + if algorithm.verify(signing_input, signature, key): + return rv + raise BadSignatureError(rv) + + def serialize_json(self, header_obj, payload, key): + """Generate a JWS JSON Serialization. The JWS JSON Serialization + represents digitally signed or MACed content as a JSON object, + per `Section 7.2`_. + + :param header_obj: A dict/list of header + :param payload: A string/dict of payload + :param key: Private key used to generate signature + :return: JWSObject + + Example ``header_obj`` of JWS JSON Serialization:: + + { + "protected: {"alg": "HS256"}, + "header": {"kid": "jose"} + } + + Pass a dict to generate flattened JSON Serialization, pass a list of + header dict to generate standard JSON Serialization. + """ + payload_segment = json_b64encode(payload) + + def _sign(jws_header): + self._validate_private_headers(jws_header) + _alg, _key = self._prepare_algorithm_key(jws_header, payload, key) + + protected_segment = json_b64encode(jws_header.protected) + signing_input = b'.'.join([protected_segment, payload_segment]) + signature = urlsafe_b64encode(_alg.sign(signing_input, _key)) + + rv = { + 'protected': to_unicode(protected_segment), + 'signature': to_unicode(signature) + } + if jws_header.header is not None: + rv['header'] = jws_header.header + return rv + + if isinstance(header_obj, dict): + data = _sign(JWSHeader.from_dict(header_obj)) + data['payload'] = to_unicode(payload_segment) + return data + + signatures = [_sign(JWSHeader.from_dict(h)) for h in header_obj] + return { + 'payload': to_unicode(payload_segment), + 'signatures': signatures + } + + def deserialize_json(self, obj, key, decode=None): + """Exact JWS JSON Serialization, and validate with the given key. + If key is not provided, it will return a dict without signature + verification. Header will still be validated. Via `Section 7.2`_. + + :param obj: text of JWS JSON Serialization + :param key: key used to verify the signature + :param decode: a function to decode payload data + :return: JWSObject + :raise: BadSignatureError + + .. _`Section 7.2`: https://tools.ietf.org/html/rfc7515#section-7.2 + """ + obj = ensure_dict(obj, 'JWS') + + payload_segment = obj.get('payload') + if payload_segment is None: + raise DecodeError('Missing "payload" value') + + payload_segment = to_bytes(payload_segment) + payload = _extract_payload(payload_segment) + if decode: + payload = decode(payload) + + if 'signatures' not in obj: + # flattened JSON JWS + jws_header, valid = self._validate_json_jws( + payload_segment, payload, obj, key) + + rv = JWSObject(jws_header, payload, 'flat') + if valid: + return rv + raise BadSignatureError(rv) + + headers = [] + is_valid = True + for header_obj in obj['signatures']: + jws_header, valid = self._validate_json_jws( + payload_segment, payload, header_obj, key) + headers.append(jws_header) + if not valid: + is_valid = False + + rv = JWSObject(headers, payload, 'json') + if is_valid: + return rv + raise BadSignatureError(rv) + + def serialize(self, header, payload, key): + """Generate a JWS Serialization. It will automatically generate a + Compact or JSON Serialization depending on the given header. If a + header is in a JSON header format, it will call + :meth:`serialize_json`, otherwise it will call + :meth:`serialize_compact`. + + :param header: A dict/list of header + :param payload: A string/dict of payload + :param key: Private key used to generate signature + :return: byte/dict + """ + if isinstance(header, (list, tuple)): + return self.serialize_json(header, payload, key) + if 'protected' in header: + return self.serialize_json(header, payload, key) + return self.serialize_compact(header, payload, key) + + def deserialize(self, s, key, decode=None): + """Deserialize JWS Serialization, both compact and JSON format. + It will automatically deserialize depending on the given JWS. + + :param s: text of JWS Compact/JSON Serialization + :param key: key used to verify the signature + :param decode: a function to decode payload data + :return: dict + :raise: BadSignatureError + + If key is not provided, it will still deserialize the serialization + without verification. + """ + if isinstance(s, dict): + return self.deserialize_json(s, key, decode) + + s = to_bytes(s) + if s.startswith(b'{') and s.endswith(b'}'): + return self.deserialize_json(s, key, decode) + return self.deserialize_compact(s, key, decode) + + def _prepare_algorithm_key(self, header, payload, key): + if 'alg' not in header: + raise MissingAlgorithmError() + + alg = header['alg'] + if self._algorithms is not None and alg not in self._algorithms: + raise UnsupportedAlgorithmError() + if alg not in self.ALGORITHMS_REGISTRY: + raise UnsupportedAlgorithmError() + + algorithm = self.ALGORITHMS_REGISTRY[alg] + if callable(key): + key = key(header, payload) + elif key is None and 'jwk' in header: + key = header['jwk'] + key = algorithm.prepare_key(key) + return algorithm, key + + def _validate_private_headers(self, header): + # only validate private headers when developers set + # private headers explicitly + if self._private_headers is not None: + names = self.REGISTERED_HEADER_PARAMETER_NAMES.copy() + names = names.union(self._private_headers) + + for k in header: + if k not in names: + raise InvalidHeaderParameterNameError(k) + + def _validate_json_jws(self, payload_segment, payload, header_obj, key): + protected_segment = header_obj.get('protected') + if not protected_segment: + raise DecodeError('Missing "protected" value') + + signature_segment = header_obj.get('signature') + if not signature_segment: + raise DecodeError('Missing "signature" value') + + protected_segment = to_bytes(protected_segment) + protected = _extract_header(protected_segment) + header = header_obj.get('header') + if header and not isinstance(header, dict): + raise DecodeError('Invalid "header" value') + + jws_header = JWSHeader(protected, header) + algorithm, key = self._prepare_algorithm_key(jws_header, payload, key) + signing_input = b'.'.join([protected_segment, payload_segment]) + signature = _extract_signature(to_bytes(signature_segment)) + if algorithm.verify(signing_input, signature, key): + return jws_header, True + return jws_header, False + + +def _extract_header(header_segment): + return extract_header(header_segment, DecodeError) + + +def _extract_signature(signature_segment): + return extract_segment(signature_segment, DecodeError, 'signature') + + +def _extract_payload(payload_segment): + return extract_segment(payload_segment, DecodeError, 'payload') diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7515/models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7515/models.py new file mode 100644 index 0000000000000000000000000000000000000000..5da3c7e0060a796e890817bf6a3b2b8789266eb4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7515/models.py @@ -0,0 +1,81 @@ +class JWSAlgorithm: + """Interface for JWS algorithm. JWA specification (RFC7518) SHOULD + implement the algorithms for JWS with this base implementation. + """ + name = None + description = None + algorithm_type = 'JWS' + algorithm_location = 'alg' + + def prepare_key(self, raw_data): + """Prepare key for signing and verifying signature.""" + raise NotImplementedError() + + def sign(self, msg, key): + """Sign the text msg with a private/sign key. + + :param msg: message bytes to be signed + :param key: private key to sign the message + :return: bytes + """ + raise NotImplementedError + + def verify(self, msg, sig, key): + """Verify the signature of text msg with a public/verify key. + + :param msg: message bytes to be signed + :param sig: result signature to be compared + :param key: public key to verify the signature + :return: boolean + """ + raise NotImplementedError + + +class JWSHeader(dict): + """Header object for JWS. It combine the protected header and unprotected + header together. JWSHeader itself is a dict of the combined dict. e.g. + + >>> protected = {'alg': 'HS256'} + >>> header = {'kid': 'a'} + >>> jws_header = JWSHeader(protected, header) + >>> print(jws_header) + {'alg': 'HS256', 'kid': 'a'} + >>> jws_header.protected == protected + >>> jws_header.header == header + + :param protected: dict of protected header + :param header: dict of unprotected header + """ + def __init__(self, protected, header): + obj = {} + if protected: + obj.update(protected) + if header: + obj.update(header) + super().__init__(obj) + self.protected = protected + self.header = header + + @classmethod + def from_dict(cls, obj): + if isinstance(obj, cls): + return obj + return cls(obj.get('protected'), obj.get('header')) + + +class JWSObject(dict): + """A dict instance to represent a JWS object.""" + def __init__(self, header, payload, type='compact'): + super().__init__( + header=header, + payload=payload, + ) + self.header = header + self.payload = payload + self.type = type + + @property + def headers(self): + """Alias of ``header`` for JSON typed JWS.""" + if self.type == 'json': + return self['header'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7516/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7516/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4a024335182116f840c27c8e518ebf7578e7577e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7516/__init__.py @@ -0,0 +1,18 @@ +""" + authlib.jose.rfc7516 + ~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + JSON Web Encryption (JWE). + + https://tools.ietf.org/html/rfc7516 +""" + +from .jwe import JsonWebEncryption +from .models import JWEAlgorithm, JWEAlgorithmWithTagAwareKeyAgreement, JWEEncAlgorithm, JWEZipAlgorithm + + +__all__ = [ + 'JsonWebEncryption', + 'JWEAlgorithm', 'JWEAlgorithmWithTagAwareKeyAgreement', 'JWEEncAlgorithm', 'JWEZipAlgorithm' +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7516/jwe.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7516/jwe.py new file mode 100644 index 0000000000000000000000000000000000000000..084bccad7a920d869aaba9f2ba2eabe255fce2a6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7516/jwe.py @@ -0,0 +1,722 @@ +from collections import OrderedDict +from copy import deepcopy + +from authlib.common.encoding import ( + to_bytes, urlsafe_b64encode, json_b64encode, to_unicode +) +from authlib.jose.rfc7516.models import JWEAlgorithmWithTagAwareKeyAgreement, JWESharedHeader, JWEHeader +from authlib.jose.util import ( + extract_header, + extract_segment, ensure_dict, +) +from authlib.jose.errors import ( + DecodeError, + MissingAlgorithmError, + UnsupportedAlgorithmError, + MissingEncryptionAlgorithmError, + UnsupportedEncryptionAlgorithmError, + UnsupportedCompressionAlgorithmError, + InvalidHeaderParameterNameError, InvalidAlgorithmForMultipleRecipientsMode, KeyMismatchError, +) + + +class JsonWebEncryption: + #: Registered Header Parameter Names defined by Section 4.1 + REGISTERED_HEADER_PARAMETER_NAMES = frozenset([ + 'alg', 'enc', 'zip', + 'jku', 'jwk', 'kid', + 'x5u', 'x5c', 'x5t', 'x5t#S256', + 'typ', 'cty', 'crit' + ]) + + ALG_REGISTRY = {} + ENC_REGISTRY = {} + ZIP_REGISTRY = {} + + def __init__(self, algorithms=None, private_headers=None): + self._algorithms = algorithms + self._private_headers = private_headers + + @classmethod + def register_algorithm(cls, algorithm): + """Register an algorithm for ``alg`` or ``enc`` or ``zip`` of JWE.""" + if not algorithm or algorithm.algorithm_type != 'JWE': + raise ValueError( + f'Invalid algorithm for JWE, {algorithm!r}') + + if algorithm.algorithm_location == 'alg': + cls.ALG_REGISTRY[algorithm.name] = algorithm + elif algorithm.algorithm_location == 'enc': + cls.ENC_REGISTRY[algorithm.name] = algorithm + elif algorithm.algorithm_location == 'zip': + cls.ZIP_REGISTRY[algorithm.name] = algorithm + + def serialize_compact(self, protected, payload, key, sender_key=None): + """Generate a JWE Compact Serialization. + + The JWE Compact Serialization represents encrypted content as a compact, + URL-safe string. This string is:: + + BASE64URL(UTF8(JWE Protected Header)) || '.' || + BASE64URL(JWE Encrypted Key) || '.' || + BASE64URL(JWE Initialization Vector) || '.' || + BASE64URL(JWE Ciphertext) || '.' || + BASE64URL(JWE Authentication Tag) + + Only one recipient is supported by the JWE Compact Serialization and + it provides no syntax to represent JWE Shared Unprotected Header, JWE + Per-Recipient Unprotected Header, or JWE AAD values. + + :param protected: A dict of protected header + :param payload: Payload (bytes or a value convertible to bytes) + :param key: Public key used to encrypt payload + :param sender_key: Sender's private key in case + JWEAlgorithmWithTagAwareKeyAgreement is used + :return: JWE compact serialization as bytes + """ + + # step 1: Prepare algorithms & key + alg = self.get_header_alg(protected) + enc = self.get_header_enc(protected) + zip_alg = self.get_header_zip(protected) + + self._validate_sender_key(sender_key, alg) + self._validate_private_headers(protected, alg) + + key = prepare_key(alg, protected, key) + if sender_key is not None: + sender_key = alg.prepare_key(sender_key) + + # self._post_validate_header(protected, algorithm) + + # step 2: Generate a random Content Encryption Key (CEK) + # use enc_alg.generate_cek() in scope of upcoming .wrap or .generate_keys_and_prepare_headers call + + # step 3: Encrypt the CEK with the recipient's public key + if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None: + # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used: + # Defer key agreement with key wrapping until authentication tag is computed + prep = alg.generate_keys_and_prepare_headers(enc, key, sender_key) + epk = prep['epk'] + cek = prep['cek'] + protected.update(prep['header']) + else: + # In any other case: + # Keep the normal steps order defined by RFC 7516 + if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement): + wrapped = alg.wrap(enc, protected, key, sender_key) + else: + wrapped = alg.wrap(enc, protected, key) + cek = wrapped['cek'] + ek = wrapped['ek'] + if 'header' in wrapped: + protected.update(wrapped['header']) + + # step 4: Generate a random JWE Initialization Vector + iv = enc.generate_iv() + + # step 5: Let the Additional Authenticated Data encryption parameter + # be ASCII(BASE64URL(UTF8(JWE Protected Header))) + protected_segment = json_b64encode(protected) + aad = to_bytes(protected_segment, 'ascii') + + # step 6: compress message if required + if zip_alg: + msg = zip_alg.compress(to_bytes(payload)) + else: + msg = to_bytes(payload) + + # step 7: perform encryption + ciphertext, tag = enc.encrypt(msg, aad, iv, cek) + + if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None: + # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used: + # Perform key agreement with key wrapping deferred at step 3 + wrapped = alg.agree_upon_key_and_wrap_cek(enc, protected, key, sender_key, epk, cek, tag) + ek = wrapped['ek'] + + # step 8: build resulting message + return b'.'.join([ + protected_segment, + urlsafe_b64encode(ek), + urlsafe_b64encode(iv), + urlsafe_b64encode(ciphertext), + urlsafe_b64encode(tag) + ]) + + def serialize_json(self, header_obj, payload, keys, sender_key=None): + """Generate a JWE JSON Serialization (in fully general syntax). + + The JWE JSON Serialization represents encrypted content as a JSON + object. This representation is neither optimized for compactness nor + URL safe. + + The following members are defined for use in top-level JSON objects + used for the fully general JWE JSON Serialization syntax: + + protected + The "protected" member MUST be present and contain the value + BASE64URL(UTF8(JWE Protected Header)) when the JWE Protected + Header value is non-empty; otherwise, it MUST be absent. These + Header Parameter values are integrity protected. + + unprotected + The "unprotected" member MUST be present and contain the value JWE + Shared Unprotected Header when the JWE Shared Unprotected Header + value is non-empty; otherwise, it MUST be absent. This value is + represented as an unencoded JSON object, rather than as a string. + These Header Parameter values are not integrity protected. + + iv + The "iv" member MUST be present and contain the value + BASE64URL(JWE Initialization Vector) when the JWE Initialization + Vector value is non-empty; otherwise, it MUST be absent. + + aad + The "aad" member MUST be present and contain the value + BASE64URL(JWE AAD)) when the JWE AAD value is non-empty; + otherwise, it MUST be absent. A JWE AAD value can be included to + supply a base64url-encoded value to be integrity protected but not + encrypted. + + ciphertext + The "ciphertext" member MUST be present and contain the value + BASE64URL(JWE Ciphertext). + + tag + The "tag" member MUST be present and contain the value + BASE64URL(JWE Authentication Tag) when the JWE Authentication Tag + value is non-empty; otherwise, it MUST be absent. + + recipients + The "recipients" member value MUST be an array of JSON objects. + Each object contains information specific to a single recipient. + This member MUST be present with exactly one array element per + recipient, even if some or all of the array element values are the + empty JSON object "{}" (which can happen when all Header Parameter + values are shared between all recipients and when no encrypted key + is used, such as when doing Direct Encryption). + + The following members are defined for use in the JSON objects that + are elements of the "recipients" array: + + header + The "header" member MUST be present and contain the value JWE Per- + Recipient Unprotected Header when the JWE Per-Recipient + Unprotected Header value is non-empty; otherwise, it MUST be + absent. This value is represented as an unencoded JSON object, + rather than as a string. These Header Parameter values are not + integrity protected. + + encrypted_key + The "encrypted_key" member MUST be present and contain the value + BASE64URL(JWE Encrypted Key) when the JWE Encrypted Key value is + non-empty; otherwise, it MUST be absent. + + This implementation assumes that "alg" and "enc" header fields are + contained in the protected or shared unprotected header. + + :param header_obj: A dict of headers (in addition optionally contains JWE AAD) + :param payload: Payload (bytes or a value convertible to bytes) + :param keys: Public keys (or a single public key) used to encrypt payload + :param sender_key: Sender's private key in case + JWEAlgorithmWithTagAwareKeyAgreement is used + :return: JWE JSON serialization (in fully general syntax) as dict + + Example of `header_obj`:: + + { + "protected": { + "alg": "ECDH-1PU+A128KW", + "enc": "A256CBC-HS512", + "apu": "QWxpY2U", + "apv": "Qm9iIGFuZCBDaGFybGll" + }, + "unprotected": { + "jku": "https://alice.example.com/keys.jwks" + }, + "recipients": [ + { + "header": { + "kid": "bob-key-2" + } + }, + { + "header": { + "kid": "2021-05-06" + } + } + ], + "aad": b'Authenticate me too.' + } + """ + if not isinstance(keys, list): # single key + keys = [keys] + + if not keys: + raise ValueError("No keys have been provided") + + header_obj = deepcopy(header_obj) + + shared_header = JWESharedHeader.from_dict(header_obj) + + recipients = header_obj.get('recipients') + if recipients is None: + recipients = [{} for _ in keys] + for i in range(len(recipients)): + if recipients[i] is None: + recipients[i] = {} + if 'header' not in recipients[i]: + recipients[i]['header'] = {} + + jwe_aad = header_obj.get('aad') + + if len(keys) != len(recipients): + raise ValueError("Count of recipient keys {} does not equal to count of recipients {}" + .format(len(keys), len(recipients))) + + # step 1: Prepare algorithms & key + alg = self.get_header_alg(shared_header) + enc = self.get_header_enc(shared_header) + zip_alg = self.get_header_zip(shared_header) + + self._validate_sender_key(sender_key, alg) + self._validate_private_headers(shared_header, alg) + for recipient in recipients: + self._validate_private_headers(recipient['header'], alg) + + for i in range(len(keys)): + keys[i] = prepare_key(alg, recipients[i]['header'], keys[i]) + if sender_key is not None: + sender_key = alg.prepare_key(sender_key) + + # self._post_validate_header(protected, algorithm) + + # step 2: Generate a random Content Encryption Key (CEK) + # use enc_alg.generate_cek() in scope of upcoming .wrap or .generate_keys_and_prepare_headers call + + # step 3: Encrypt the CEK with the recipient's public key + preset = alg.generate_preset(enc, keys[0]) + if 'cek' in preset: + cek = preset['cek'] + else: + cek = None + if len(keys) > 1 and cek is None: + raise InvalidAlgorithmForMultipleRecipientsMode(alg.name) + if 'header' in preset: + shared_header.update_protected(preset['header']) + + if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None: + # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used: + # Defer key agreement with key wrapping until authentication tag is computed + epks = [] + for i in range(len(keys)): + prep = alg.generate_keys_and_prepare_headers(enc, keys[i], sender_key, preset) + if cek is None: + cek = prep['cek'] + epks.append(prep['epk']) + recipients[i]['header'].update(prep['header']) + else: + # In any other case: + # Keep the normal steps order defined by RFC 7516 + for i in range(len(keys)): + if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement): + wrapped = alg.wrap(enc, shared_header, keys[i], sender_key, preset) + else: + wrapped = alg.wrap(enc, shared_header, keys[i], preset) + if cek is None: + cek = wrapped['cek'] + recipients[i]['encrypted_key'] = wrapped['ek'] + if 'header' in wrapped: + recipients[i]['header'].update(wrapped['header']) + + # step 4: Generate a random JWE Initialization Vector + iv = enc.generate_iv() + + # step 5: Compute the Encoded Protected Header value + # BASE64URL(UTF8(JWE Protected Header)). If the JWE Protected Header + # is not present, let this value be the empty string. + # Let the Additional Authenticated Data encryption parameter be + # ASCII(Encoded Protected Header). However, if a JWE AAD value is + # present, instead let the Additional Authenticated Data encryption + # parameter be ASCII(Encoded Protected Header || '.' || BASE64URL(JWE AAD)). + aad = json_b64encode(shared_header.protected) if shared_header.protected else b'' + if jwe_aad is not None: + aad += b'.' + urlsafe_b64encode(jwe_aad) + aad = to_bytes(aad, 'ascii') + + # step 6: compress message if required + if zip_alg: + msg = zip_alg.compress(to_bytes(payload)) + else: + msg = to_bytes(payload) + + # step 7: perform encryption + ciphertext, tag = enc.encrypt(msg, aad, iv, cek) + + if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None: + # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used: + # Perform key agreement with key wrapping deferred at step 3 + for i in range(len(keys)): + wrapped = alg.agree_upon_key_and_wrap_cek(enc, shared_header, keys[i], sender_key, epks[i], cek, tag) + recipients[i]['encrypted_key'] = wrapped['ek'] + + # step 8: build resulting message + obj = OrderedDict() + + if shared_header.protected: + obj['protected'] = to_unicode(json_b64encode(shared_header.protected)) + + if shared_header.unprotected: + obj['unprotected'] = shared_header.unprotected + + for recipient in recipients: + if not recipient['header']: + del recipient['header'] + recipient['encrypted_key'] = to_unicode(urlsafe_b64encode(recipient['encrypted_key'])) + for member in set(recipient.keys()): + if member not in {'header', 'encrypted_key'}: + del recipient[member] + obj['recipients'] = recipients + + if jwe_aad is not None: + obj['aad'] = to_unicode(urlsafe_b64encode(jwe_aad)) + + obj['iv'] = to_unicode(urlsafe_b64encode(iv)) + + obj['ciphertext'] = to_unicode(urlsafe_b64encode(ciphertext)) + + obj['tag'] = to_unicode(urlsafe_b64encode(tag)) + + return obj + + def serialize(self, header, payload, key, sender_key=None): + """Generate a JWE Serialization. + + It will automatically generate a compact or JSON serialization depending + on `header` argument. If `header` is a dict with "protected", + "unprotected" and/or "recipients" keys, it will call `serialize_json`, + otherwise it will call `serialize_compact`. + + :param header: A dict of header(s) + :param payload: Payload (bytes or a value convertible to bytes) + :param key: Public key(s) used to encrypt payload + :param sender_key: Sender's private key in case + JWEAlgorithmWithTagAwareKeyAgreement is used + :return: JWE compact serialization as bytes or + JWE JSON serialization as dict + """ + if 'protected' in header or 'unprotected' in header or 'recipients' in header: + return self.serialize_json(header, payload, key, sender_key) + + return self.serialize_compact(header, payload, key, sender_key) + + def deserialize_compact(self, s, key, decode=None, sender_key=None): + """Extract JWE Compact Serialization. + + :param s: JWE Compact Serialization as bytes + :param key: Private key used to decrypt payload + (optionally can be a tuple of kid and essentially key) + :param decode: Function to decode payload data + :param sender_key: Sender's public key in case + JWEAlgorithmWithTagAwareKeyAgreement is used + :return: dict with `header` and `payload` keys where `header` value is + a dict containing protected header fields + """ + try: + s = to_bytes(s) + protected_s, ek_s, iv_s, ciphertext_s, tag_s = s.rsplit(b'.') + except ValueError: + raise DecodeError('Not enough segments') + + protected = extract_header(protected_s, DecodeError) + ek = extract_segment(ek_s, DecodeError, 'encryption key') + iv = extract_segment(iv_s, DecodeError, 'initialization vector') + ciphertext = extract_segment(ciphertext_s, DecodeError, 'ciphertext') + tag = extract_segment(tag_s, DecodeError, 'authentication tag') + + alg = self.get_header_alg(protected) + enc = self.get_header_enc(protected) + zip_alg = self.get_header_zip(protected) + + self._validate_sender_key(sender_key, alg) + self._validate_private_headers(protected, alg) + + if isinstance(key, tuple) and len(key) == 2: + # Ignore separately provided kid, extract essentially key only + key = key[1] + + key = prepare_key(alg, protected, key) + + if sender_key is not None: + sender_key = alg.prepare_key(sender_key) + + if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement): + # For a JWE algorithm with tag-aware key agreement: + if alg.key_size is not None: + # In case key agreement with key wrapping mode is used: + # Provide authentication tag to .unwrap method + cek = alg.unwrap(enc, ek, protected, key, sender_key, tag) + else: + # Otherwise, don't provide authentication tag to .unwrap method + cek = alg.unwrap(enc, ek, protected, key, sender_key) + else: + # For any other JWE algorithm: + # Don't provide authentication tag to .unwrap method + cek = alg.unwrap(enc, ek, protected, key) + + aad = to_bytes(protected_s, 'ascii') + msg = enc.decrypt(ciphertext, aad, iv, tag, cek) + + if zip_alg: + payload = zip_alg.decompress(to_bytes(msg)) + else: + payload = msg + + if decode: + payload = decode(payload) + return {'header': protected, 'payload': payload} + + def deserialize_json(self, obj, key, decode=None, sender_key=None): + """Extract JWE JSON Serialization. + + :param obj: JWE JSON Serialization as dict or str + :param key: Private key used to decrypt payload + (optionally can be a tuple of kid and essentially key) + :param decode: Function to decode payload data + :param sender_key: Sender's public key in case + JWEAlgorithmWithTagAwareKeyAgreement is used + :return: dict with `header` and `payload` keys where `header` value is + a dict containing `protected`, `unprotected`, `recipients` and/or + `aad` keys + """ + obj = ensure_dict(obj, 'JWE') + obj = deepcopy(obj) + + if 'protected' in obj: + protected = extract_header(to_bytes(obj['protected']), DecodeError) + else: + protected = None + + unprotected = obj.get('unprotected') + + recipients = obj['recipients'] + for recipient in recipients: + if 'header' not in recipient: + recipient['header'] = {} + recipient['encrypted_key'] = extract_segment( + to_bytes(recipient['encrypted_key']), DecodeError, 'encrypted key') + + if 'aad' in obj: + jwe_aad = extract_segment(to_bytes(obj['aad']), DecodeError, 'JWE AAD') + else: + jwe_aad = None + + iv = extract_segment(to_bytes(obj['iv']), DecodeError, 'initialization vector') + + ciphertext = extract_segment(to_bytes(obj['ciphertext']), DecodeError, 'ciphertext') + + tag = extract_segment(to_bytes(obj['tag']), DecodeError, 'authentication tag') + + shared_header = JWESharedHeader(protected, unprotected) + + alg = self.get_header_alg(shared_header) + enc = self.get_header_enc(shared_header) + zip_alg = self.get_header_zip(shared_header) + + self._validate_sender_key(sender_key, alg) + self._validate_private_headers(shared_header, alg) + for recipient in recipients: + self._validate_private_headers(recipient['header'], alg) + + kid = None + if isinstance(key, tuple) and len(key) == 2: + # Extract separately provided kid and essentially key + kid = key[0] + key = key[1] + + key = alg.prepare_key(key) + + if kid is None: + # If kid has not been provided separately, try to get it from key itself + kid = key.kid + + if sender_key is not None: + sender_key = alg.prepare_key(sender_key) + + def _unwrap_with_sender_key_and_tag(ek, header): + return alg.unwrap(enc, ek, header, key, sender_key, tag) + + def _unwrap_with_sender_key_and_without_tag(ek, header): + return alg.unwrap(enc, ek, header, key, sender_key) + + def _unwrap_without_sender_key_and_tag(ek, header): + return alg.unwrap(enc, ek, header, key) + + def _unwrap_for_matching_recipient(unwrap_func): + if kid is not None: + for recipient in recipients: + if recipient['header'].get('kid') == kid: + header = JWEHeader(protected, unprotected, recipient['header']) + return unwrap_func(recipient['encrypted_key'], header) + + # Since no explicit match has been found, iterate over all the recipients + error = None + for recipient in recipients: + header = JWEHeader(protected, unprotected, recipient['header']) + try: + return unwrap_func(recipient['encrypted_key'], header) + except Exception as e: + error = e + else: + if error is None: + raise KeyMismatchError() + else: + raise error + + if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement): + # For a JWE algorithm with tag-aware key agreement: + if alg.key_size is not None: + # In case key agreement with key wrapping mode is used: + # Provide authentication tag to .unwrap method + cek = _unwrap_for_matching_recipient(_unwrap_with_sender_key_and_tag) + else: + # Otherwise, don't provide authentication tag to .unwrap method + cek = _unwrap_for_matching_recipient(_unwrap_with_sender_key_and_without_tag) + else: + # For any other JWE algorithm: + # Don't provide authentication tag to .unwrap method + cek = _unwrap_for_matching_recipient(_unwrap_without_sender_key_and_tag) + + aad = to_bytes(obj.get('protected', '')) + if 'aad' in obj: + aad += b'.' + to_bytes(obj['aad']) + aad = to_bytes(aad, 'ascii') + + msg = enc.decrypt(ciphertext, aad, iv, tag, cek) + + if zip_alg: + payload = zip_alg.decompress(to_bytes(msg)) + else: + payload = msg + + if decode: + payload = decode(payload) + + for recipient in recipients: + if not recipient['header']: + del recipient['header'] + for member in set(recipient.keys()): + if member != 'header': + del recipient[member] + + header = {} + if protected: + header['protected'] = protected + if unprotected: + header['unprotected'] = unprotected + header['recipients'] = recipients + if jwe_aad is not None: + header['aad'] = jwe_aad + + return { + 'header': header, + 'payload': payload + } + + def deserialize(self, obj, key, decode=None, sender_key=None): + """Extract a JWE Serialization. + + It supports both compact and JSON serialization. + + :param obj: JWE compact serialization as bytes or + JWE JSON serialization as dict or str + :param key: Private key used to decrypt payload + (optionally can be a tuple of kid and essentially key) + :param decode: Function to decode payload data + :param sender_key: Sender's public key in case + JWEAlgorithmWithTagAwareKeyAgreement is used + :return: dict with `header` and `payload` keys + """ + if isinstance(obj, dict): + return self.deserialize_json(obj, key, decode, sender_key) + + obj = to_bytes(obj) + if obj.startswith(b'{') and obj.endswith(b'}'): + return self.deserialize_json(obj, key, decode, sender_key) + + return self.deserialize_compact(obj, key, decode, sender_key) + + @staticmethod + def parse_json(obj): + """Parse JWE JSON Serialization. + + :param obj: JWE JSON Serialization as str or dict + :return: Parsed JWE JSON Serialization as dict if `obj` is an str, + or `obj` as is if `obj` is already a dict + """ + return ensure_dict(obj, 'JWE') + + def get_header_alg(self, header): + if 'alg' not in header: + raise MissingAlgorithmError() + + alg = header['alg'] + if self._algorithms is not None and alg not in self._algorithms: + raise UnsupportedAlgorithmError() + if alg not in self.ALG_REGISTRY: + raise UnsupportedAlgorithmError() + return self.ALG_REGISTRY[alg] + + def get_header_enc(self, header): + if 'enc' not in header: + raise MissingEncryptionAlgorithmError() + enc = header['enc'] + if self._algorithms is not None and enc not in self._algorithms: + raise UnsupportedEncryptionAlgorithmError() + if enc not in self.ENC_REGISTRY: + raise UnsupportedEncryptionAlgorithmError() + return self.ENC_REGISTRY[enc] + + def get_header_zip(self, header): + if 'zip' in header: + z = header['zip'] + if self._algorithms is not None and z not in self._algorithms: + raise UnsupportedCompressionAlgorithmError() + if z not in self.ZIP_REGISTRY: + raise UnsupportedCompressionAlgorithmError() + return self.ZIP_REGISTRY[z] + + def _validate_sender_key(self, sender_key, alg): + if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement): + if sender_key is None: + raise ValueError("{} algorithm requires sender_key but passed sender_key value is None" + .format(alg.name)) + else: + if sender_key is not None: + raise ValueError("{} algorithm does not use sender_key but passed sender_key value is not None" + .format(alg.name)) + + def _validate_private_headers(self, header, alg): + # only validate private headers when developers set + # private headers explicitly + if self._private_headers is None: + return + + names = self.REGISTERED_HEADER_PARAMETER_NAMES.copy() + names = names.union(self._private_headers) + + if alg.EXTRA_HEADERS: + names = names.union(alg.EXTRA_HEADERS) + + for k in header: + if k not in names: + raise InvalidHeaderParameterNameError(k) + + +def prepare_key(alg, header, key): + if callable(key): + key = key(header, None) + elif key is None and 'jwk' in header: + key = header['jwk'] + return alg.prepare_key(key) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7516/models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7516/models.py new file mode 100644 index 0000000000000000000000000000000000000000..279563cf949f5781bdeaa593c7beea46dc08415e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7516/models.py @@ -0,0 +1,148 @@ +import os +from abc import ABCMeta + + +class JWEAlgorithmBase(metaclass=ABCMeta): + """Base interface for all JWE algorithms. + """ + EXTRA_HEADERS = None + + name = None + description = None + algorithm_type = 'JWE' + algorithm_location = 'alg' + + def prepare_key(self, raw_data): + raise NotImplementedError + + def generate_preset(self, enc_alg, key): + raise NotImplementedError + + +class JWEAlgorithm(JWEAlgorithmBase, metaclass=ABCMeta): + """Interface for JWE algorithm conforming to RFC7518. + JWA specification (RFC7518) SHOULD implement the algorithms for JWE with this base implementation. + """ + def wrap(self, enc_alg, headers, key, preset=None): + raise NotImplementedError + + def unwrap(self, enc_alg, ek, headers, key): + raise NotImplementedError + + +class JWEAlgorithmWithTagAwareKeyAgreement(JWEAlgorithmBase, metaclass=ABCMeta): + """Interface for JWE algorithm with tag-aware key agreement (in key agreement with key wrapping mode). + ECDH-1PU is an example of such an algorithm. + """ + def generate_keys_and_prepare_headers(self, enc_alg, key, sender_key, preset=None): + raise NotImplementedError + + def agree_upon_key_and_wrap_cek(self, enc_alg, headers, key, sender_key, epk, cek, tag): + raise NotImplementedError + + def wrap(self, enc_alg, headers, key, sender_key, preset=None): + raise NotImplementedError + + def unwrap(self, enc_alg, ek, headers, key, sender_key, tag=None): + raise NotImplementedError + + +class JWEEncAlgorithm: + name = None + description = None + algorithm_type = 'JWE' + algorithm_location = 'enc' + + IV_SIZE = None + CEK_SIZE = None + + def generate_cek(self): + return os.urandom(self.CEK_SIZE // 8) + + def generate_iv(self): + return os.urandom(self.IV_SIZE // 8) + + def check_iv(self, iv): + if len(iv) * 8 != self.IV_SIZE: + raise ValueError('Invalid "iv" size') + + def encrypt(self, msg, aad, iv, key): + """Encrypt the given "msg" text. + + :param msg: text to be encrypt in bytes + :param aad: additional authenticated data in bytes + :param iv: initialization vector in bytes + :param key: encrypted key in bytes + :return: (ciphertext, tag) + """ + raise NotImplementedError + + def decrypt(self, ciphertext, aad, iv, tag, key): + """Decrypt the given cipher text. + + :param ciphertext: ciphertext in bytes + :param aad: additional authenticated data in bytes + :param iv: initialization vector in bytes + :param tag: authentication tag in bytes + :param key: encrypted key in bytes + :return: message + """ + raise NotImplementedError + + +class JWEZipAlgorithm: + name = None + description = None + algorithm_type = 'JWE' + algorithm_location = 'zip' + + def compress(self, s): + raise NotImplementedError + + def decompress(self, s): + raise NotImplementedError + + +class JWESharedHeader(dict): + """Shared header object for JWE. + + Combines protected header and shared unprotected header together. + """ + def __init__(self, protected, unprotected): + obj = {} + if protected: + obj.update(protected) + if unprotected: + obj.update(unprotected) + super().__init__(obj) + self.protected = protected if protected else {} + self.unprotected = unprotected if unprotected else {} + + def update_protected(self, addition): + self.update(addition) + self.protected.update(addition) + + @classmethod + def from_dict(cls, obj): + if isinstance(obj, cls): + return obj + return cls(obj.get('protected'), obj.get('unprotected')) + + +class JWEHeader(dict): + """Header object for JWE. + + Combines protected header, shared unprotected header and specific recipient's unprotected header together. + """ + def __init__(self, protected, unprotected, header): + obj = {} + if protected: + obj.update(protected) + if unprotected: + obj.update(unprotected) + if header: + obj.update(header) + super().__init__(obj) + self.protected = protected if protected else {} + self.unprotected = unprotected if unprotected else {} + self.header = header if header else {} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3fbbb2d8c936d8625d54717ea966170c3628007 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/__init__.py @@ -0,0 +1,17 @@ +""" + authlib.jose.rfc7517 + ~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + JSON Web Key (JWK). + + https://tools.ietf.org/html/rfc7517 +""" +from ._cryptography_key import load_pem_key +from .base_key import Key +from .asymmetric_key import AsymmetricKey +from .key_set import KeySet +from .jwk import JsonWebKey + + +__all__ = ['Key', 'AsymmetricKey', 'KeySet', 'JsonWebKey', 'load_pem_key'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/_cryptography_key.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/_cryptography_key.py new file mode 100644 index 0000000000000000000000000000000000000000..f7194a37fbd1fbc139636447bb1502e8a31ec9fb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/_cryptography_key.py @@ -0,0 +1,34 @@ +from cryptography.x509 import load_pem_x509_certificate +from cryptography.hazmat.primitives.serialization import ( + load_pem_private_key, load_pem_public_key, load_ssh_public_key, +) +from cryptography.hazmat.backends import default_backend +from authlib.common.encoding import to_bytes + + +def load_pem_key(raw, ssh_type=None, key_type=None, password=None): + raw = to_bytes(raw) + + if ssh_type and raw.startswith(ssh_type): + return load_ssh_public_key(raw, backend=default_backend()) + + if key_type == 'public': + return load_pem_public_key(raw, backend=default_backend()) + + if key_type == 'private' or password is not None: + return load_pem_private_key(raw, password=password, backend=default_backend()) + + if b'PUBLIC' in raw: + return load_pem_public_key(raw, backend=default_backend()) + + if b'PRIVATE' in raw: + return load_pem_private_key(raw, password=password, backend=default_backend()) + + if b'CERTIFICATE' in raw: + cert = load_pem_x509_certificate(raw, default_backend()) + return cert.public_key() + + try: + return load_pem_private_key(raw, password=password, backend=default_backend()) + except ValueError: + return load_pem_public_key(raw, backend=default_backend()) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/asymmetric_key.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/asymmetric_key.py new file mode 100644 index 0000000000000000000000000000000000000000..35b1937c1d0fed25a5b1eedc19d6413b9a9d13f9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/asymmetric_key.py @@ -0,0 +1,191 @@ +from authlib.common.encoding import to_bytes +from cryptography.hazmat.primitives.serialization import ( + Encoding, PrivateFormat, PublicFormat, + BestAvailableEncryption, NoEncryption, +) +from ._cryptography_key import load_pem_key +from .base_key import Key + + +class AsymmetricKey(Key): + """This is the base class for a JSON Web Key.""" + PUBLIC_KEY_FIELDS = [] + PRIVATE_KEY_FIELDS = [] + PRIVATE_KEY_CLS = bytes + PUBLIC_KEY_CLS = bytes + SSH_PUBLIC_PREFIX = b'' + + def __init__(self, private_key=None, public_key=None, options=None): + super().__init__(options) + self.private_key = private_key + self.public_key = public_key + + @property + def public_only(self): + if self.private_key: + return False + if 'd' in self.tokens: + return False + return True + + def get_op_key(self, operation): + """Get the raw key for the given key_op. This method will also + check if the given key_op is supported by this key. + + :param operation: key operation value, such as "sign", "encrypt". + :return: raw key + """ + self.check_key_op(operation) + if operation in self.PUBLIC_KEY_OPS: + return self.get_public_key() + return self.get_private_key() + + def get_public_key(self): + if self.public_key: + return self.public_key + + private_key = self.get_private_key() + if private_key: + return private_key.public_key() + + return self.public_key + + def get_private_key(self): + if self.private_key: + return self.private_key + + if self.tokens: + self.load_raw_key() + return self.private_key + + def load_raw_key(self): + if 'd' in self.tokens: + self.private_key = self.load_private_key() + else: + self.public_key = self.load_public_key() + + def load_dict_key(self): + if self.private_key: + self._dict_data.update(self.dumps_private_key()) + else: + self._dict_data.update(self.dumps_public_key()) + + def dumps_private_key(self): + raise NotImplementedError() + + def dumps_public_key(self): + raise NotImplementedError() + + def load_private_key(self): + raise NotImplementedError() + + def load_public_key(self): + raise NotImplementedError() + + def as_dict(self, is_private=False, **params): + """Represent this key as a dict of the JSON Web Key.""" + tokens = self.tokens + if is_private and 'd' not in tokens: + raise ValueError('This is a public key') + + kid = tokens.get('kid') + if 'd' in tokens and not is_private: + # filter out private fields + tokens = {k: tokens[k] for k in tokens if k in self.PUBLIC_KEY_FIELDS} + tokens['kty'] = self.kty + if kid: + tokens['kid'] = kid + + if not kid: + tokens['kid'] = self.thumbprint() + + tokens.update(params) + return tokens + + def as_key(self, is_private=False): + """Represent this key as raw key.""" + if is_private: + return self.get_private_key() + return self.get_public_key() + + def as_bytes(self, encoding=None, is_private=False, password=None): + """Export key into PEM/DER format bytes. + + :param encoding: "PEM" or "DER" + :param is_private: export private key or public key + :param password: encrypt private key with password + :return: bytes + """ + + if encoding is None or encoding == 'PEM': + encoding = Encoding.PEM + elif encoding == 'DER': + encoding = Encoding.DER + else: + raise ValueError(f'Invalid encoding: {encoding!r}') + + raw_key = self.as_key(is_private) + if is_private: + if not raw_key: + raise ValueError('This is a public key') + if password is None: + encryption_algorithm = NoEncryption() + else: + encryption_algorithm = BestAvailableEncryption(to_bytes(password)) + return raw_key.private_bytes( + encoding=encoding, + format=PrivateFormat.PKCS8, + encryption_algorithm=encryption_algorithm, + ) + return raw_key.public_bytes( + encoding=encoding, + format=PublicFormat.SubjectPublicKeyInfo, + ) + + def as_pem(self, is_private=False, password=None): + return self.as_bytes(is_private=is_private, password=password) + + def as_der(self, is_private=False, password=None): + return self.as_bytes(encoding='DER', is_private=is_private, password=password) + + @classmethod + def import_dict_key(cls, raw, options=None): + cls.check_required_fields(raw) + key = cls(options=options) + key._dict_data = raw + return key + + @classmethod + def import_key(cls, raw, options=None): + if isinstance(raw, cls): + if options is not None: + raw.options.update(options) + return raw + + if isinstance(raw, cls.PUBLIC_KEY_CLS): + key = cls(public_key=raw, options=options) + elif isinstance(raw, cls.PRIVATE_KEY_CLS): + key = cls(private_key=raw, options=options) + elif isinstance(raw, dict): + key = cls.import_dict_key(raw, options) + else: + if options is not None: + password = options.pop('password', None) + else: + password = None + raw_key = load_pem_key(raw, cls.SSH_PUBLIC_PREFIX, password=password) + if isinstance(raw_key, cls.PUBLIC_KEY_CLS): + key = cls(public_key=raw_key, options=options) + elif isinstance(raw_key, cls.PRIVATE_KEY_CLS): + key = cls(private_key=raw_key, options=options) + else: + raise ValueError('Invalid data for importing key') + return key + + @classmethod + def validate_raw_key(cls, key): + return isinstance(key, cls.PUBLIC_KEY_CLS) or isinstance(key, cls.PRIVATE_KEY_CLS) + + @classmethod + def generate_key(cls, crv_or_size, options=None, is_private=False): + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/base_key.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/base_key.py new file mode 100644 index 0000000000000000000000000000000000000000..1afe8d48700ad9805703493b163f3bbd075063b9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/base_key.py @@ -0,0 +1,118 @@ +import hashlib +from collections import OrderedDict +from authlib.common.encoding import ( + json_dumps, + to_bytes, + to_unicode, + urlsafe_b64encode, +) +from ..errors import InvalidUseError + + +class Key: + """This is the base class for a JSON Web Key.""" + kty = '_' + + ALLOWED_PARAMS = [ + 'use', 'key_ops', 'alg', 'kid', + 'x5u', 'x5c', 'x5t', 'x5t#S256' + ] + + PRIVATE_KEY_OPS = [ + 'sign', 'decrypt', 'unwrapKey', + ] + PUBLIC_KEY_OPS = [ + 'verify', 'encrypt', 'wrapKey', + ] + + REQUIRED_JSON_FIELDS = [] + + def __init__(self, options=None): + self.options = options or {} + self._dict_data = {} + + @property + def tokens(self): + if not self._dict_data: + self.load_dict_key() + + rv = dict(self._dict_data) + rv['kty'] = self.kty + for k in self.ALLOWED_PARAMS: + if k not in rv and k in self.options: + rv[k] = self.options[k] + return rv + + @property + def kid(self): + return self.tokens.get('kid') + + def keys(self): + return self.tokens.keys() + + def __getitem__(self, item): + return self.tokens[item] + + @property + def public_only(self): + raise NotImplementedError() + + def load_raw_key(self): + raise NotImplementedError() + + def load_dict_key(self): + raise NotImplementedError() + + def check_key_op(self, operation): + """Check if the given key_op is supported by this key. + + :param operation: key operation value, such as "sign", "encrypt". + :raise: ValueError + """ + key_ops = self.tokens.get('key_ops') + if key_ops is not None and operation not in key_ops: + raise ValueError(f'Unsupported key_op "{operation}"') + + if operation in self.PRIVATE_KEY_OPS and self.public_only: + raise ValueError(f'Invalid key_op "{operation}" for public key') + + use = self.tokens.get('use') + if use: + if operation in ['sign', 'verify']: + if use != 'sig': + raise InvalidUseError() + elif operation in ['decrypt', 'encrypt', 'wrapKey', 'unwrapKey']: + if use != 'enc': + raise InvalidUseError() + + def as_dict(self, is_private=False, **params): + raise NotImplementedError() + + def as_json(self, is_private=False, **params): + """Represent this key as a JSON string.""" + obj = self.as_dict(is_private, **params) + return json_dumps(obj) + + def thumbprint(self): + """Implementation of RFC7638 JSON Web Key (JWK) Thumbprint.""" + fields = list(self.REQUIRED_JSON_FIELDS) + fields.append('kty') + fields.sort() + data = OrderedDict() + + for k in fields: + data[k] = self.tokens[k] + + json_data = json_dumps(data) + digest_data = hashlib.sha256(to_bytes(json_data)).digest() + return to_unicode(urlsafe_b64encode(digest_data)) + + @classmethod + def check_required_fields(cls, data): + for k in cls.REQUIRED_JSON_FIELDS: + if k not in data: + raise ValueError(f'Missing required field: "{k}"') + + @classmethod + def validate_raw_key(cls, key): + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/jwk.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/jwk.py new file mode 100644 index 0000000000000000000000000000000000000000..b1578c49c5afecc54adc35e98293179530b0cf0a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/jwk.py @@ -0,0 +1,64 @@ +from authlib.common.encoding import json_loads +from .key_set import KeySet +from ._cryptography_key import load_pem_key + + +class JsonWebKey: + JWK_KEY_CLS = {} + + @classmethod + def generate_key(cls, kty, crv_or_size, options=None, is_private=False): + """Generate a Key with the given key type, curve name or bit size. + + :param kty: string of ``oct``, ``RSA``, ``EC``, ``OKP`` + :param crv_or_size: curve name or bit size + :param options: a dict of other options for Key + :param is_private: create a private key or public key + :return: Key instance + """ + key_cls = cls.JWK_KEY_CLS[kty] + return key_cls.generate_key(crv_or_size, options, is_private) + + @classmethod + def import_key(cls, raw, options=None): + """Import a Key from bytes, string, PEM or dict. + + :return: Key instance + """ + kty = None + if options is not None: + kty = options.get('kty') + + if kty is None and isinstance(raw, dict): + kty = raw.get('kty') + + if kty is None: + raw_key = load_pem_key(raw) + for _kty in cls.JWK_KEY_CLS: + key_cls = cls.JWK_KEY_CLS[_kty] + if key_cls.validate_raw_key(raw_key): + return key_cls.import_key(raw_key, options) + + key_cls = cls.JWK_KEY_CLS[kty] + return key_cls.import_key(raw, options) + + @classmethod + def import_key_set(cls, raw): + """Import KeySet from string, dict or a list of keys. + + :return: KeySet instance + """ + raw = _transform_raw_key(raw) + if isinstance(raw, dict) and 'keys' in raw: + keys = raw.get('keys') + return KeySet([cls.import_key(k) for k in keys]) + raise ValueError('Invalid key set format') + + +def _transform_raw_key(raw): + if isinstance(raw, str) and \ + raw.startswith('{') and raw.endswith('}'): + return json_loads(raw) + elif isinstance(raw, (tuple, list)): + return {'keys': raw} + return raw diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/key_set.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/key_set.py new file mode 100644 index 0000000000000000000000000000000000000000..3416ce9bb578af19b5db5d2e2b3bbb7e855c1ef1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7517/key_set.py @@ -0,0 +1,29 @@ +from authlib.common.encoding import json_dumps + + +class KeySet: + """This class represents a JSON Web Key Set.""" + + def __init__(self, keys): + self.keys = keys + + def as_dict(self, is_private=False, **params): + """Represent this key as a dict of the JSON Web Key Set.""" + return {'keys': [k.as_dict(is_private, **params) for k in self.keys]} + + def as_json(self, is_private=False, **params): + """Represent this key set as a JSON string.""" + obj = self.as_dict(is_private, **params) + return json_dumps(obj) + + def find_by_kid(self, kid): + """Find the key matches the given kid value. + + :param kid: A string of kid + :return: Key instance + :raise: ValueError + """ + for k in self.keys: + if k.kid == kid: + return k + raise ValueError('Invalid JSON Web Key Set') diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..360f6c685e12c14583480bcec404886fb996dbad --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/__init__.py @@ -0,0 +1,35 @@ +from .oct_key import OctKey +from .rsa_key import RSAKey +from .ec_key import ECKey +from .jws_algs import JWS_ALGORITHMS +from .jwe_algs import JWE_ALG_ALGORITHMS, AESAlgorithm, ECDHESAlgorithm, u32be_len_input +from .jwe_encs import JWE_ENC_ALGORITHMS, CBCHS2EncAlgorithm +from .jwe_zips import DeflateZipAlgorithm + + +def register_jws_rfc7518(cls): + for algorithm in JWS_ALGORITHMS: + cls.register_algorithm(algorithm) + + +def register_jwe_rfc7518(cls): + for algorithm in JWE_ALG_ALGORITHMS: + cls.register_algorithm(algorithm) + + for algorithm in JWE_ENC_ALGORITHMS: + cls.register_algorithm(algorithm) + + cls.register_algorithm(DeflateZipAlgorithm()) + + +__all__ = [ + 'register_jws_rfc7518', + 'register_jwe_rfc7518', + 'OctKey', + 'RSAKey', + 'ECKey', + 'u32be_len_input', + 'AESAlgorithm', + 'ECDHESAlgorithm', + 'CBCHS2EncAlgorithm', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/ec_key.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/ec_key.py new file mode 100644 index 0000000000000000000000000000000000000000..05f0c044404f94b47fd60c9e1fb3aa8f81d5c962 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/ec_key.py @@ -0,0 +1,101 @@ +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.asymmetric.ec import ( + EllipticCurvePublicKey, EllipticCurvePrivateKeyWithSerialization, + EllipticCurvePrivateNumbers, EllipticCurvePublicNumbers, + SECP256R1, SECP384R1, SECP521R1, SECP256K1, +) +from cryptography.hazmat.backends import default_backend +from authlib.common.encoding import base64_to_int, int_to_base64 +from ..rfc7517 import AsymmetricKey + + +class ECKey(AsymmetricKey): + """Key class of the ``EC`` key type.""" + + kty = 'EC' + DSS_CURVES = { + 'P-256': SECP256R1, + 'P-384': SECP384R1, + 'P-521': SECP521R1, + # https://tools.ietf.org/html/rfc8812#section-3.1 + 'secp256k1': SECP256K1, + } + CURVES_DSS = { + SECP256R1.name: 'P-256', + SECP384R1.name: 'P-384', + SECP521R1.name: 'P-521', + SECP256K1.name: 'secp256k1', + } + REQUIRED_JSON_FIELDS = ['crv', 'x', 'y'] + + PUBLIC_KEY_FIELDS = REQUIRED_JSON_FIELDS + PRIVATE_KEY_FIELDS = ['crv', 'd', 'x', 'y'] + + PUBLIC_KEY_CLS = EllipticCurvePublicKey + PRIVATE_KEY_CLS = EllipticCurvePrivateKeyWithSerialization + SSH_PUBLIC_PREFIX = b'ecdsa-sha2-' + + def exchange_shared_key(self, pubkey): + # # used in ECDHESAlgorithm + private_key = self.get_private_key() + if private_key: + return private_key.exchange(ec.ECDH(), pubkey) + raise ValueError('Invalid key for exchanging shared key') + + @property + def curve_key_size(self): + raw_key = self.get_private_key() + if not raw_key: + raw_key = self.public_key + return raw_key.curve.key_size + + def load_private_key(self): + curve = self.DSS_CURVES[self._dict_data['crv']]() + public_numbers = EllipticCurvePublicNumbers( + base64_to_int(self._dict_data['x']), + base64_to_int(self._dict_data['y']), + curve, + ) + private_numbers = EllipticCurvePrivateNumbers( + base64_to_int(self.tokens['d']), + public_numbers + ) + return private_numbers.private_key(default_backend()) + + def load_public_key(self): + curve = self.DSS_CURVES[self._dict_data['crv']]() + public_numbers = EllipticCurvePublicNumbers( + base64_to_int(self._dict_data['x']), + base64_to_int(self._dict_data['y']), + curve, + ) + return public_numbers.public_key(default_backend()) + + def dumps_private_key(self): + numbers = self.private_key.private_numbers() + return { + 'crv': self.CURVES_DSS[self.private_key.curve.name], + 'x': int_to_base64(numbers.public_numbers.x), + 'y': int_to_base64(numbers.public_numbers.y), + 'd': int_to_base64(numbers.private_value), + } + + def dumps_public_key(self): + numbers = self.public_key.public_numbers() + return { + 'crv': self.CURVES_DSS[numbers.curve.name], + 'x': int_to_base64(numbers.x), + 'y': int_to_base64(numbers.y) + } + + @classmethod + def generate_key(cls, crv='P-256', options=None, is_private=False) -> 'ECKey': + if crv not in cls.DSS_CURVES: + raise ValueError(f'Invalid crv value: "{crv}"') + raw_key = ec.generate_private_key( + curve=cls.DSS_CURVES[crv](), + backend=default_backend(), + ) + if not is_private: + raw_key = raw_key.public_key() + return cls.import_key(raw_key, options=options) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jwe_algs.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jwe_algs.py new file mode 100644 index 0000000000000000000000000000000000000000..b57654a9f28c1498a0868cde60dd2caa5edf12db --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jwe_algs.py @@ -0,0 +1,349 @@ +import os +import struct +from cryptography.hazmat.primitives.asymmetric import padding +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.keywrap import ( + aes_key_wrap, + aes_key_unwrap +) +from cryptography.hazmat.primitives.ciphers import Cipher +from cryptography.hazmat.primitives.ciphers.algorithms import AES +from cryptography.hazmat.primitives.ciphers.modes import GCM +from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHash +from authlib.common.encoding import ( + to_bytes, to_native, + urlsafe_b64decode, + urlsafe_b64encode +) +from authlib.jose.rfc7516 import JWEAlgorithm +from .rsa_key import RSAKey +from .ec_key import ECKey +from .oct_key import OctKey + + +class DirectAlgorithm(JWEAlgorithm): + name = 'dir' + description = 'Direct use of a shared symmetric key' + + def prepare_key(self, raw_data): + return OctKey.import_key(raw_data) + + def generate_preset(self, enc_alg, key): + return {} + + def wrap(self, enc_alg, headers, key, preset=None): + cek = key.get_op_key('encrypt') + if len(cek) * 8 != enc_alg.CEK_SIZE: + raise ValueError('Invalid "cek" length') + return {'ek': b'', 'cek': cek} + + def unwrap(self, enc_alg, ek, headers, key): + cek = key.get_op_key('decrypt') + if len(cek) * 8 != enc_alg.CEK_SIZE: + raise ValueError('Invalid "cek" length') + return cek + + +class RSAAlgorithm(JWEAlgorithm): + #: A key of size 2048 bits or larger MUST be used with these algorithms + #: RSA1_5, RSA-OAEP, RSA-OAEP-256 + key_size = 2048 + + def __init__(self, name, description, pad_fn): + self.name = name + self.description = description + self.padding = pad_fn + + def prepare_key(self, raw_data): + return RSAKey.import_key(raw_data) + + def generate_preset(self, enc_alg, key): + cek = enc_alg.generate_cek() + return {'cek': cek} + + def wrap(self, enc_alg, headers, key, preset=None): + if preset and 'cek' in preset: + cek = preset['cek'] + else: + cek = enc_alg.generate_cek() + + op_key = key.get_op_key('wrapKey') + if op_key.key_size < self.key_size: + raise ValueError('A key of size 2048 bits or larger MUST be used') + ek = op_key.encrypt(cek, self.padding) + return {'ek': ek, 'cek': cek} + + def unwrap(self, enc_alg, ek, headers, key): + # it will raise ValueError if failed + op_key = key.get_op_key('unwrapKey') + cek = op_key.decrypt(ek, self.padding) + if len(cek) * 8 != enc_alg.CEK_SIZE: + raise ValueError('Invalid "cek" length') + return cek + + +class AESAlgorithm(JWEAlgorithm): + def __init__(self, key_size): + self.name = f'A{key_size}KW' + self.description = f'AES Key Wrap using {key_size}-bit key' + self.key_size = key_size + + def prepare_key(self, raw_data): + return OctKey.import_key(raw_data) + + def generate_preset(self, enc_alg, key): + cek = enc_alg.generate_cek() + return {'cek': cek} + + def _check_key(self, key): + if len(key) * 8 != self.key_size: + raise ValueError( + f'A key of size {self.key_size} bits is required.') + + def wrap_cek(self, cek, key): + op_key = key.get_op_key('wrapKey') + self._check_key(op_key) + ek = aes_key_wrap(op_key, cek, default_backend()) + return {'ek': ek, 'cek': cek} + + def wrap(self, enc_alg, headers, key, preset=None): + if preset and 'cek' in preset: + cek = preset['cek'] + else: + cek = enc_alg.generate_cek() + return self.wrap_cek(cek, key) + + def unwrap(self, enc_alg, ek, headers, key): + op_key = key.get_op_key('unwrapKey') + self._check_key(op_key) + cek = aes_key_unwrap(op_key, ek, default_backend()) + if len(cek) * 8 != enc_alg.CEK_SIZE: + raise ValueError('Invalid "cek" length') + return cek + + +class AESGCMAlgorithm(JWEAlgorithm): + EXTRA_HEADERS = frozenset(['iv', 'tag']) + + def __init__(self, key_size): + self.name = f'A{key_size}GCMKW' + self.description = f'Key wrapping with AES GCM using {key_size}-bit key' + self.key_size = key_size + + def prepare_key(self, raw_data): + return OctKey.import_key(raw_data) + + def generate_preset(self, enc_alg, key): + cek = enc_alg.generate_cek() + return {'cek': cek} + + def _check_key(self, key): + if len(key) * 8 != self.key_size: + raise ValueError( + f'A key of size {self.key_size} bits is required.') + + def wrap(self, enc_alg, headers, key, preset=None): + if preset and 'cek' in preset: + cek = preset['cek'] + else: + cek = enc_alg.generate_cek() + + op_key = key.get_op_key('wrapKey') + self._check_key(op_key) + + #: https://tools.ietf.org/html/rfc7518#section-4.7.1.1 + #: The "iv" (initialization vector) Header Parameter value is the + #: base64url-encoded representation of the 96-bit IV value + iv_size = 96 + iv = os.urandom(iv_size // 8) + + cipher = Cipher(AES(op_key), GCM(iv), backend=default_backend()) + enc = cipher.encryptor() + ek = enc.update(cek) + enc.finalize() + + h = { + 'iv': to_native(urlsafe_b64encode(iv)), + 'tag': to_native(urlsafe_b64encode(enc.tag)) + } + return {'ek': ek, 'cek': cek, 'header': h} + + def unwrap(self, enc_alg, ek, headers, key): + op_key = key.get_op_key('unwrapKey') + self._check_key(op_key) + + iv = headers.get('iv') + if not iv: + raise ValueError('Missing "iv" in headers') + + tag = headers.get('tag') + if not tag: + raise ValueError('Missing "tag" in headers') + + iv = urlsafe_b64decode(to_bytes(iv)) + tag = urlsafe_b64decode(to_bytes(tag)) + + cipher = Cipher(AES(op_key), GCM(iv, tag), backend=default_backend()) + d = cipher.decryptor() + cek = d.update(ek) + d.finalize() + if len(cek) * 8 != enc_alg.CEK_SIZE: + raise ValueError('Invalid "cek" length') + return cek + + +class ECDHESAlgorithm(JWEAlgorithm): + EXTRA_HEADERS = ['epk', 'apu', 'apv'] + ALLOWED_KEY_CLS = ECKey + + # https://tools.ietf.org/html/rfc7518#section-4.6 + def __init__(self, key_size=None): + if key_size is None: + self.name = 'ECDH-ES' + self.description = 'ECDH-ES in the Direct Key Agreement mode' + else: + self.name = f'ECDH-ES+A{key_size}KW' + self.description = ( + 'ECDH-ES using Concat KDF and CEK wrapped ' + 'with A{}KW').format(key_size) + self.key_size = key_size + self.aeskw = AESAlgorithm(key_size) + + def prepare_key(self, raw_data): + if isinstance(raw_data, self.ALLOWED_KEY_CLS): + return raw_data + return ECKey.import_key(raw_data) + + def generate_preset(self, enc_alg, key): + epk = self._generate_ephemeral_key(key) + h = self._prepare_headers(epk) + preset = {'epk': epk, 'header': h} + if self.key_size is not None: + cek = enc_alg.generate_cek() + preset['cek'] = cek + return preset + + def compute_fixed_info(self, headers, bit_size): + # AlgorithmID + if self.key_size is None: + alg_id = u32be_len_input(headers['enc']) + else: + alg_id = u32be_len_input(headers['alg']) + + # PartyUInfo + apu_info = u32be_len_input(headers.get('apu'), True) + + # PartyVInfo + apv_info = u32be_len_input(headers.get('apv'), True) + + # SuppPubInfo + pub_info = struct.pack('>I', bit_size) + + return alg_id + apu_info + apv_info + pub_info + + def compute_derived_key(self, shared_key, fixed_info, bit_size): + ckdf = ConcatKDFHash( + algorithm=hashes.SHA256(), + length=bit_size // 8, + otherinfo=fixed_info, + backend=default_backend() + ) + return ckdf.derive(shared_key) + + def deliver(self, key, pubkey, headers, bit_size): + shared_key = key.exchange_shared_key(pubkey) + fixed_info = self.compute_fixed_info(headers, bit_size) + return self.compute_derived_key(shared_key, fixed_info, bit_size) + + def _generate_ephemeral_key(self, key): + return key.generate_key(key['crv'], is_private=True) + + def _prepare_headers(self, epk): + # REQUIRED_JSON_FIELDS contains only public fields + pub_epk = {k: epk[k] for k in epk.REQUIRED_JSON_FIELDS} + pub_epk['kty'] = epk.kty + return {'epk': pub_epk} + + def wrap(self, enc_alg, headers, key, preset=None): + if self.key_size is None: + bit_size = enc_alg.CEK_SIZE + else: + bit_size = self.key_size + + if preset and 'epk' in preset: + epk = preset['epk'] + h = {} + else: + epk = self._generate_ephemeral_key(key) + h = self._prepare_headers(epk) + + public_key = key.get_op_key('wrapKey') + dk = self.deliver(epk, public_key, headers, bit_size) + + if self.key_size is None: + return {'ek': b'', 'cek': dk, 'header': h} + + if preset and 'cek' in preset: + preset_for_kw = {'cek': preset['cek']} + else: + preset_for_kw = None + + kek = self.aeskw.prepare_key(dk) + rv = self.aeskw.wrap(enc_alg, headers, kek, preset_for_kw) + rv['header'] = h + return rv + + def unwrap(self, enc_alg, ek, headers, key): + if 'epk' not in headers: + raise ValueError('Missing "epk" in headers') + + if self.key_size is None: + bit_size = enc_alg.CEK_SIZE + else: + bit_size = self.key_size + + epk = key.import_key(headers['epk']) + public_key = epk.get_op_key('wrapKey') + dk = self.deliver(key, public_key, headers, bit_size) + + if self.key_size is None: + return dk + + kek = self.aeskw.prepare_key(dk) + return self.aeskw.unwrap(enc_alg, ek, headers, kek) + + +def u32be_len_input(s, base64=False): + if not s: + return b'\x00\x00\x00\x00' + if base64: + s = urlsafe_b64decode(to_bytes(s)) + else: + s = to_bytes(s) + return struct.pack('>I', len(s)) + s + + +JWE_ALG_ALGORITHMS = [ + DirectAlgorithm(), # dir + RSAAlgorithm('RSA1_5', 'RSAES-PKCS1-v1_5', padding.PKCS1v15()), + RSAAlgorithm( + 'RSA-OAEP', 'RSAES OAEP using default parameters', + padding.OAEP(padding.MGF1(hashes.SHA1()), hashes.SHA1(), None)), + RSAAlgorithm( + 'RSA-OAEP-256', 'RSAES OAEP using SHA-256 and MGF1 with SHA-256', + padding.OAEP(padding.MGF1(hashes.SHA256()), hashes.SHA256(), None)), + + AESAlgorithm(128), # A128KW + AESAlgorithm(192), # A192KW + AESAlgorithm(256), # A256KW + AESGCMAlgorithm(128), # A128GCMKW + AESGCMAlgorithm(192), # A192GCMKW + AESGCMAlgorithm(256), # A256GCMKW + ECDHESAlgorithm(None), # ECDH-ES + ECDHESAlgorithm(128), # ECDH-ES+A128KW + ECDHESAlgorithm(192), # ECDH-ES+A192KW + ECDHESAlgorithm(256), # ECDH-ES+A256KW +] + +# 'PBES2-HS256+A128KW': '', +# 'PBES2-HS384+A192KW': '', +# 'PBES2-HS512+A256KW': '', diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jwe_encs.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jwe_encs.py new file mode 100644 index 0000000000000000000000000000000000000000..f951d10122e19f4f429c630df32b9e3802f18aa2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jwe_encs.py @@ -0,0 +1,144 @@ +""" + authlib.jose.rfc7518 + ~~~~~~~~~~~~~~~~~~~~ + + Cryptographic Algorithms for Cryptographic Algorithms for Content + Encryption per `Section 5`_. + + .. _`Section 5`: https://tools.ietf.org/html/rfc7518#section-5 +""" +import hmac +import hashlib +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.ciphers import Cipher +from cryptography.hazmat.primitives.ciphers.algorithms import AES +from cryptography.hazmat.primitives.ciphers.modes import GCM, CBC +from cryptography.hazmat.primitives.padding import PKCS7 +from cryptography.exceptions import InvalidTag +from ..rfc7516 import JWEEncAlgorithm +from .util import encode_int + + +class CBCHS2EncAlgorithm(JWEEncAlgorithm): + # The IV used is a 128-bit value generated randomly or + # pseudo-randomly for use in the cipher. + IV_SIZE = 128 + + def __init__(self, key_size, hash_type): + self.name = f'A{key_size}CBC-HS{hash_type}' + tpl = 'AES_{}_CBC_HMAC_SHA_{} authenticated encryption algorithm' + self.description = tpl.format(key_size, hash_type) + + # bit length + self.key_size = key_size + # byte length + self.key_len = key_size // 8 + + self.CEK_SIZE = key_size * 2 + self.hash_alg = getattr(hashlib, f'sha{hash_type}') + + def _hmac(self, ciphertext, aad, iv, key): + al = encode_int(len(aad) * 8, 64) + msg = aad + iv + ciphertext + al + d = hmac.new(key, msg, self.hash_alg).digest() + return d[:self.key_len] + + def encrypt(self, msg, aad, iv, key): + """Key Encryption with AES_CBC_HMAC_SHA2. + + :param msg: text to be encrypt in bytes + :param aad: additional authenticated data in bytes + :param iv: initialization vector in bytes + :param key: encrypted key in bytes + :return: (ciphertext, iv, tag) + """ + self.check_iv(iv) + hkey = key[:self.key_len] + ekey = key[self.key_len:] + + pad = PKCS7(AES.block_size).padder() + padded_data = pad.update(msg) + pad.finalize() + + cipher = Cipher(AES(ekey), CBC(iv), backend=default_backend()) + enc = cipher.encryptor() + ciphertext = enc.update(padded_data) + enc.finalize() + tag = self._hmac(ciphertext, aad, iv, hkey) + return ciphertext, tag + + def decrypt(self, ciphertext, aad, iv, tag, key): + """Key Decryption with AES AES_CBC_HMAC_SHA2. + + :param ciphertext: ciphertext in bytes + :param aad: additional authenticated data in bytes + :param iv: initialization vector in bytes + :param tag: authentication tag in bytes + :param key: encrypted key in bytes + :return: message + """ + self.check_iv(iv) + hkey = key[:self.key_len] + dkey = key[self.key_len:] + + _tag = self._hmac(ciphertext, aad, iv, hkey) + if not hmac.compare_digest(_tag, tag): + raise InvalidTag() + + cipher = Cipher(AES(dkey), CBC(iv), backend=default_backend()) + d = cipher.decryptor() + data = d.update(ciphertext) + d.finalize() + unpad = PKCS7(AES.block_size).unpadder() + return unpad.update(data) + unpad.finalize() + + +class GCMEncAlgorithm(JWEEncAlgorithm): + # Use of an IV of size 96 bits is REQUIRED with this algorithm. + # https://tools.ietf.org/html/rfc7518#section-5.3 + IV_SIZE = 96 + + def __init__(self, key_size): + self.name = f'A{key_size}GCM' + self.description = f'AES GCM using {key_size}-bit key' + self.key_size = key_size + self.CEK_SIZE = key_size + + def encrypt(self, msg, aad, iv, key): + """Key Encryption with AES GCM + + :param msg: text to be encrypt in bytes + :param aad: additional authenticated data in bytes + :param iv: initialization vector in bytes + :param key: encrypted key in bytes + :return: (ciphertext, iv, tag) + """ + self.check_iv(iv) + cipher = Cipher(AES(key), GCM(iv), backend=default_backend()) + enc = cipher.encryptor() + enc.authenticate_additional_data(aad) + ciphertext = enc.update(msg) + enc.finalize() + return ciphertext, enc.tag + + def decrypt(self, ciphertext, aad, iv, tag, key): + """Key Decryption with AES GCM + + :param ciphertext: ciphertext in bytes + :param aad: additional authenticated data in bytes + :param iv: initialization vector in bytes + :param tag: authentication tag in bytes + :param key: encrypted key in bytes + :return: message + """ + self.check_iv(iv) + cipher = Cipher(AES(key), GCM(iv, tag), backend=default_backend()) + d = cipher.decryptor() + d.authenticate_additional_data(aad) + return d.update(ciphertext) + d.finalize() + + +JWE_ENC_ALGORITHMS = [ + CBCHS2EncAlgorithm(128, 256), # A128CBC-HS256 + CBCHS2EncAlgorithm(192, 384), # A192CBC-HS384 + CBCHS2EncAlgorithm(256, 512), # A256CBC-HS512 + GCMEncAlgorithm(128), # A128GCM + GCMEncAlgorithm(192), # A192GCM + GCMEncAlgorithm(256), # A256GCM +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jwe_zips.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jwe_zips.py new file mode 100644 index 0000000000000000000000000000000000000000..239686104089a78409e0c871a2e8a04cd40e700d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jwe_zips.py @@ -0,0 +1,21 @@ +import zlib +from ..rfc7516 import JWEZipAlgorithm, JsonWebEncryption + + +class DeflateZipAlgorithm(JWEZipAlgorithm): + name = 'DEF' + description = 'DEFLATE' + + def compress(self, s): + """Compress bytes data with DEFLATE algorithm.""" + data = zlib.compress(s) + # drop gzip headers and tail + return data[2:-4] + + def decompress(self, s): + """Decompress DEFLATE bytes data.""" + return zlib.decompress(s, -zlib.MAX_WBITS) + + +def register_jwe_rfc7518(): + JsonWebEncryption.register_algorithm(DeflateZipAlgorithm()) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jws_algs.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jws_algs.py new file mode 100644 index 0000000000000000000000000000000000000000..2c02840337c68fe1e062a11f62156f200aea73c4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/jws_algs.py @@ -0,0 +1,215 @@ +""" + authlib.jose.rfc7518 + ~~~~~~~~~~~~~~~~~~~~ + + "alg" (Algorithm) Header Parameter Values for JWS per `Section 3`_. + + .. _`Section 3`: https://tools.ietf.org/html/rfc7518#section-3 +""" + +import hmac +import hashlib +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric.utils import ( + decode_dss_signature, encode_dss_signature +) +from cryptography.hazmat.primitives.asymmetric.ec import ECDSA +from cryptography.hazmat.primitives.asymmetric import padding +from cryptography.exceptions import InvalidSignature +from ..rfc7515 import JWSAlgorithm +from .oct_key import OctKey +from .rsa_key import RSAKey +from .ec_key import ECKey +from .util import encode_int, decode_int + + +class NoneAlgorithm(JWSAlgorithm): + name = 'none' + description = 'No digital signature or MAC performed' + + def prepare_key(self, raw_data): + return None + + def sign(self, msg, key): + return b'' + + def verify(self, msg, sig, key): + return False + + +class HMACAlgorithm(JWSAlgorithm): + """HMAC using SHA algorithms for JWS. Available algorithms: + + - HS256: HMAC using SHA-256 + - HS384: HMAC using SHA-384 + - HS512: HMAC using SHA-512 + """ + SHA256 = hashlib.sha256 + SHA384 = hashlib.sha384 + SHA512 = hashlib.sha512 + + def __init__(self, sha_type): + self.name = f'HS{sha_type}' + self.description = f'HMAC using SHA-{sha_type}' + self.hash_alg = getattr(self, f'SHA{sha_type}') + + def prepare_key(self, raw_data): + return OctKey.import_key(raw_data) + + def sign(self, msg, key): + # it is faster than the one in cryptography + op_key = key.get_op_key('sign') + return hmac.new(op_key, msg, self.hash_alg).digest() + + def verify(self, msg, sig, key): + op_key = key.get_op_key('verify') + v_sig = hmac.new(op_key, msg, self.hash_alg).digest() + return hmac.compare_digest(sig, v_sig) + + +class RSAAlgorithm(JWSAlgorithm): + """RSA using SHA algorithms for JWS. Available algorithms: + + - RS256: RSASSA-PKCS1-v1_5 using SHA-256 + - RS384: RSASSA-PKCS1-v1_5 using SHA-384 + - RS512: RSASSA-PKCS1-v1_5 using SHA-512 + """ + SHA256 = hashes.SHA256 + SHA384 = hashes.SHA384 + SHA512 = hashes.SHA512 + + def __init__(self, sha_type): + self.name = f'RS{sha_type}' + self.description = f'RSASSA-PKCS1-v1_5 using SHA-{sha_type}' + self.hash_alg = getattr(self, f'SHA{sha_type}') + self.padding = padding.PKCS1v15() + + def prepare_key(self, raw_data): + return RSAKey.import_key(raw_data) + + def sign(self, msg, key): + op_key = key.get_op_key('sign') + return op_key.sign(msg, self.padding, self.hash_alg()) + + def verify(self, msg, sig, key): + op_key = key.get_op_key('verify') + try: + op_key.verify(sig, msg, self.padding, self.hash_alg()) + return True + except InvalidSignature: + return False + + +class ECAlgorithm(JWSAlgorithm): + """ECDSA using SHA algorithms for JWS. Available algorithms: + + - ES256: ECDSA using P-256 and SHA-256 + - ES384: ECDSA using P-384 and SHA-384 + - ES512: ECDSA using P-521 and SHA-512 + """ + SHA256 = hashes.SHA256 + SHA384 = hashes.SHA384 + SHA512 = hashes.SHA512 + + def __init__(self, name, curve, sha_type): + self.name = name + self.curve = curve + self.description = f'ECDSA using {self.curve} and SHA-{sha_type}' + self.hash_alg = getattr(self, f'SHA{sha_type}') + + def prepare_key(self, raw_data): + key = ECKey.import_key(raw_data) + if key['crv'] != self.curve: + raise ValueError(f'Key for "{self.name}" not supported, only "{self.curve}" allowed') + return key + + def sign(self, msg, key): + op_key = key.get_op_key('sign') + der_sig = op_key.sign(msg, ECDSA(self.hash_alg())) + r, s = decode_dss_signature(der_sig) + size = key.curve_key_size + return encode_int(r, size) + encode_int(s, size) + + def verify(self, msg, sig, key): + key_size = key.curve_key_size + length = (key_size + 7) // 8 + + if len(sig) != 2 * length: + return False + + r = decode_int(sig[:length]) + s = decode_int(sig[length:]) + der_sig = encode_dss_signature(r, s) + + try: + op_key = key.get_op_key('verify') + op_key.verify(der_sig, msg, ECDSA(self.hash_alg())) + return True + except InvalidSignature: + return False + + +class RSAPSSAlgorithm(JWSAlgorithm): + """RSASSA-PSS using SHA algorithms for JWS. Available algorithms: + + - PS256: RSASSA-PSS using SHA-256 and MGF1 with SHA-256 + - PS384: RSASSA-PSS using SHA-384 and MGF1 with SHA-384 + - PS512: RSASSA-PSS using SHA-512 and MGF1 with SHA-512 + """ + SHA256 = hashes.SHA256 + SHA384 = hashes.SHA384 + SHA512 = hashes.SHA512 + + def __init__(self, sha_type): + self.name = f'PS{sha_type}' + tpl = 'RSASSA-PSS using SHA-{} and MGF1 with SHA-{}' + self.description = tpl.format(sha_type, sha_type) + self.hash_alg = getattr(self, f'SHA{sha_type}') + + def prepare_key(self, raw_data): + return RSAKey.import_key(raw_data) + + def sign(self, msg, key): + op_key = key.get_op_key('sign') + return op_key.sign( + msg, + padding.PSS( + mgf=padding.MGF1(self.hash_alg()), + salt_length=self.hash_alg.digest_size + ), + self.hash_alg() + ) + + def verify(self, msg, sig, key): + op_key = key.get_op_key('verify') + try: + op_key.verify( + sig, + msg, + padding.PSS( + mgf=padding.MGF1(self.hash_alg()), + salt_length=self.hash_alg.digest_size + ), + self.hash_alg() + ) + return True + except InvalidSignature: + return False + + +JWS_ALGORITHMS = [ + NoneAlgorithm(), # none + HMACAlgorithm(256), # HS256 + HMACAlgorithm(384), # HS384 + HMACAlgorithm(512), # HS512 + RSAAlgorithm(256), # RS256 + RSAAlgorithm(384), # RS384 + RSAAlgorithm(512), # RS512 + ECAlgorithm('ES256', 'P-256', 256), + ECAlgorithm('ES384', 'P-384', 384), + ECAlgorithm('ES512', 'P-521', 512), + ECAlgorithm('ES256K', 'secp256k1', 256), # defined in RFC8812 + RSAPSSAlgorithm(256), # PS256 + RSAPSSAlgorithm(384), # PS384 + RSAPSSAlgorithm(512), # PS512 +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/oct_key.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/oct_key.py new file mode 100644 index 0000000000000000000000000000000000000000..1db321a70d806b1d34b6454aa6b4b5b0b24f4951 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/oct_key.py @@ -0,0 +1,80 @@ +from authlib.common.encoding import ( + to_bytes, to_unicode, + urlsafe_b64encode, urlsafe_b64decode, +) +from authlib.common.security import generate_token +from ..rfc7517 import Key + + +class OctKey(Key): + """Key class of the ``oct`` key type.""" + + kty = 'oct' + REQUIRED_JSON_FIELDS = ['k'] + + def __init__(self, raw_key=None, options=None): + super().__init__(options) + self.raw_key = raw_key + + @property + def public_only(self): + return False + + def get_op_key(self, operation): + """Get the raw key for the given key_op. This method will also + check if the given key_op is supported by this key. + + :param operation: key operation value, such as "sign", "encrypt". + :return: raw key + """ + self.check_key_op(operation) + if not self.raw_key: + self.load_raw_key() + return self.raw_key + + def load_raw_key(self): + self.raw_key = urlsafe_b64decode(to_bytes(self.tokens['k'])) + + def load_dict_key(self): + k = to_unicode(urlsafe_b64encode(self.raw_key)) + self._dict_data = {'kty': self.kty, 'k': k} + + def as_dict(self, is_private=False, **params): + tokens = self.tokens + if 'kid' not in tokens: + tokens['kid'] = self.thumbprint() + + tokens.update(params) + return tokens + + @classmethod + def validate_raw_key(cls, key): + return isinstance(key, bytes) + + @classmethod + def import_key(cls, raw, options=None): + """Import a key from bytes, string, or dict data.""" + if isinstance(raw, cls): + if options is not None: + raw.options.update(options) + return raw + + if isinstance(raw, dict): + cls.check_required_fields(raw) + key = cls(options=options) + key._dict_data = raw + else: + raw_key = to_bytes(raw) + key = cls(raw_key=raw_key, options=options) + return key + + @classmethod + def generate_key(cls, key_size=256, options=None, is_private=True): + """Generate a ``OctKey`` with the given bit size.""" + if not is_private: + raise ValueError('oct key can not be generated as public') + + if key_size % 8 != 0: + raise ValueError('Invalid bit size for oct key') + + return cls.import_key(generate_token(key_size // 8), options) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/rsa_key.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/rsa_key.py new file mode 100644 index 0000000000000000000000000000000000000000..53bd9958e92752a917b3931cdaa612e6e9d50fce --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/rsa_key.py @@ -0,0 +1,123 @@ +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.asymmetric.rsa import ( + RSAPublicKey, RSAPrivateKeyWithSerialization, + RSAPrivateNumbers, RSAPublicNumbers, + rsa_recover_prime_factors, rsa_crt_dmp1, rsa_crt_dmq1, rsa_crt_iqmp +) +from cryptography.hazmat.backends import default_backend +from authlib.common.encoding import base64_to_int, int_to_base64 +from ..rfc7517 import AsymmetricKey + + +class RSAKey(AsymmetricKey): + """Key class of the ``RSA`` key type.""" + + kty = 'RSA' + PUBLIC_KEY_CLS = RSAPublicKey + PRIVATE_KEY_CLS = RSAPrivateKeyWithSerialization + + PUBLIC_KEY_FIELDS = ['e', 'n'] + PRIVATE_KEY_FIELDS = ['d', 'dp', 'dq', 'e', 'n', 'p', 'q', 'qi'] + REQUIRED_JSON_FIELDS = ['e', 'n'] + SSH_PUBLIC_PREFIX = b'ssh-rsa' + + def dumps_private_key(self): + numbers = self.private_key.private_numbers() + return { + 'n': int_to_base64(numbers.public_numbers.n), + 'e': int_to_base64(numbers.public_numbers.e), + 'd': int_to_base64(numbers.d), + 'p': int_to_base64(numbers.p), + 'q': int_to_base64(numbers.q), + 'dp': int_to_base64(numbers.dmp1), + 'dq': int_to_base64(numbers.dmq1), + 'qi': int_to_base64(numbers.iqmp) + } + + def dumps_public_key(self): + numbers = self.public_key.public_numbers() + return { + 'n': int_to_base64(numbers.n), + 'e': int_to_base64(numbers.e) + } + + def load_private_key(self): + obj = self._dict_data + + if 'oth' in obj: # pragma: no cover + # https://tools.ietf.org/html/rfc7518#section-6.3.2.7 + raise ValueError('"oth" is not supported yet') + + public_numbers = RSAPublicNumbers( + base64_to_int(obj['e']), base64_to_int(obj['n'])) + + if has_all_prime_factors(obj): + numbers = RSAPrivateNumbers( + d=base64_to_int(obj['d']), + p=base64_to_int(obj['p']), + q=base64_to_int(obj['q']), + dmp1=base64_to_int(obj['dp']), + dmq1=base64_to_int(obj['dq']), + iqmp=base64_to_int(obj['qi']), + public_numbers=public_numbers) + else: + d = base64_to_int(obj['d']) + p, q = rsa_recover_prime_factors( + public_numbers.n, d, public_numbers.e) + numbers = RSAPrivateNumbers( + d=d, + p=p, + q=q, + dmp1=rsa_crt_dmp1(d, p), + dmq1=rsa_crt_dmq1(d, q), + iqmp=rsa_crt_iqmp(p, q), + public_numbers=public_numbers) + + return numbers.private_key(default_backend()) + + def load_public_key(self): + numbers = RSAPublicNumbers( + base64_to_int(self._dict_data['e']), + base64_to_int(self._dict_data['n']) + ) + return numbers.public_key(default_backend()) + + @classmethod + def generate_key(cls, key_size=2048, options=None, is_private=False) -> 'RSAKey': + if key_size < 512: + raise ValueError('key_size must not be less than 512') + if key_size % 8 != 0: + raise ValueError('Invalid key_size for RSAKey') + raw_key = rsa.generate_private_key( + public_exponent=65537, + key_size=key_size, + backend=default_backend(), + ) + if not is_private: + raw_key = raw_key.public_key() + return cls.import_key(raw_key, options=options) + + @classmethod + def import_dict_key(cls, raw, options=None): + cls.check_required_fields(raw) + key = cls(options=options) + key._dict_data = raw + if 'd' in raw and not has_all_prime_factors(raw): + # reload dict key + key.load_raw_key() + key.load_dict_key() + return key + + +def has_all_prime_factors(obj): + props = ['p', 'q', 'dp', 'dq', 'qi'] + props_found = [prop in obj for prop in props] + if all(props_found): + return True + + if any(props_found): + raise ValueError( + 'RSA key must include all parameters ' + 'if any are present besides d') + + return False diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/util.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/util.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d13ec1f18c68a34a9b1adaa1460423486908a9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7518/util.py @@ -0,0 +1,12 @@ +import binascii + + +def encode_int(num, bits): + length = ((bits + 7) // 8) * 2 + padded_hex = '%0*x' % (length, num) + big_endian = binascii.a2b_hex(padded_hex.encode('ascii')) + return big_endian + + +def decode_int(b): + return int(binascii.b2a_hex(b), 16) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7519/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7519/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5eea5b7fc5bfeef0fefaf91a331d32a45684df01 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7519/__init__.py @@ -0,0 +1,15 @@ +""" + authlib.jose.rfc7519 + ~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + JSON Web Token (JWT). + + https://tools.ietf.org/html/rfc7519 +""" + +from .jwt import JsonWebToken +from .claims import BaseClaims, JWTClaims + + +__all__ = ['JsonWebToken', 'BaseClaims', 'JWTClaims'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7519/claims.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7519/claims.py new file mode 100644 index 0000000000000000000000000000000000000000..6a9877bc18c5fcb1be5274f810cdc49529bc6009 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7519/claims.py @@ -0,0 +1,227 @@ +import time +from authlib.jose.errors import ( + MissingClaimError, + InvalidClaimError, + ExpiredTokenError, + InvalidTokenError, +) + + +class BaseClaims(dict): + """Payload claims for JWT, which contains a validate interface. + + :param payload: the payload dict of JWT + :param header: the header dict of JWT + :param options: validate options + :param params: other params + + An example on ``options`` parameter, the format is inspired by + `OpenID Connect Claims`_:: + + { + "iss": { + "essential": True, + "values": ["https://example.com", "https://example.org"] + }, + "sub": { + "essential": True + "value": "248289761001" + }, + "jti": { + "validate": validate_jti + } + } + + .. _`OpenID Connect Claims`: + http://openid.net/specs/openid-connect-core-1_0.html#IndividualClaimsRequests + """ + REGISTERED_CLAIMS = [] + + def __init__(self, payload, header, options=None, params=None): + super().__init__(payload) + self.header = header + self.options = options or {} + self.params = params or {} + + def __getattr__(self, key): + try: + return object.__getattribute__(self, key) + except AttributeError as error: + if key in self.REGISTERED_CLAIMS: + return self.get(key) + raise error + + def _validate_essential_claims(self): + for k in self.options: + if self.options[k].get('essential'): + if k not in self: + raise MissingClaimError(k) + elif not self.get(k): + raise InvalidClaimError(k) + + def _validate_claim_value(self, claim_name): + option = self.options.get(claim_name) + if not option: + return + + value = self.get(claim_name) + option_value = option.get('value') + if option_value and value != option_value: + raise InvalidClaimError(claim_name) + + option_values = option.get('values') + if option_values and value not in option_values: + raise InvalidClaimError(claim_name) + + validate = option.get('validate') + if validate and not validate(self, value): + raise InvalidClaimError(claim_name) + + def get_registered_claims(self): + rv = {} + for k in self.REGISTERED_CLAIMS: + if k in self: + rv[k] = self[k] + return rv + + +class JWTClaims(BaseClaims): + REGISTERED_CLAIMS = ['iss', 'sub', 'aud', 'exp', 'nbf', 'iat', 'jti'] + + def validate(self, now=None, leeway=0): + """Validate everything in claims payload.""" + self._validate_essential_claims() + + if now is None: + now = int(time.time()) + + self.validate_iss() + self.validate_sub() + self.validate_aud() + self.validate_exp(now, leeway) + self.validate_nbf(now, leeway) + self.validate_iat(now, leeway) + self.validate_jti() + + # Validate custom claims + for key in self.options.keys(): + if key not in self.REGISTERED_CLAIMS: + self._validate_claim_value(key) + + def validate_iss(self): + """The "iss" (issuer) claim identifies the principal that issued the + JWT. The processing of this claim is generally application specific. + The "iss" value is a case-sensitive string containing a StringOrURI + value. Use of this claim is OPTIONAL. + """ + self._validate_claim_value('iss') + + def validate_sub(self): + """The "sub" (subject) claim identifies the principal that is the + subject of the JWT. The claims in a JWT are normally statements + about the subject. The subject value MUST either be scoped to be + locally unique in the context of the issuer or be globally unique. + The processing of this claim is generally application specific. The + "sub" value is a case-sensitive string containing a StringOrURI + value. Use of this claim is OPTIONAL. + """ + self._validate_claim_value('sub') + + def validate_aud(self): + """The "aud" (audience) claim identifies the recipients that the JWT is + intended for. Each principal intended to process the JWT MUST + identify itself with a value in the audience claim. If the principal + processing the claim does not identify itself with a value in the + "aud" claim when this claim is present, then the JWT MUST be + rejected. In the general case, the "aud" value is an array of case- + sensitive strings, each containing a StringOrURI value. In the + special case when the JWT has one audience, the "aud" value MAY be a + single case-sensitive string containing a StringOrURI value. The + interpretation of audience values is generally application specific. + Use of this claim is OPTIONAL. + """ + aud_option = self.options.get('aud') + aud = self.get('aud') + if not aud_option or not aud: + return + + aud_values = aud_option.get('values') + if not aud_values: + aud_value = aud_option.get('value') + if aud_value: + aud_values = [aud_value] + + if not aud_values: + return + + if isinstance(self['aud'], list): + aud_list = self['aud'] + else: + aud_list = [self['aud']] + + if not any([v in aud_list for v in aud_values]): + raise InvalidClaimError('aud') + + def validate_exp(self, now, leeway): + """The "exp" (expiration time) claim identifies the expiration time on + or after which the JWT MUST NOT be accepted for processing. The + processing of the "exp" claim requires that the current date/time + MUST be before the expiration date/time listed in the "exp" claim. + Implementers MAY provide for some small leeway, usually no more than + a few minutes, to account for clock skew. Its value MUST be a number + containing a NumericDate value. Use of this claim is OPTIONAL. + """ + if 'exp' in self: + exp = self['exp'] + if not _validate_numeric_time(exp): + raise InvalidClaimError('exp') + if exp < (now - leeway): + raise ExpiredTokenError() + + def validate_nbf(self, now, leeway): + """The "nbf" (not before) claim identifies the time before which the JWT + MUST NOT be accepted for processing. The processing of the "nbf" + claim requires that the current date/time MUST be after or equal to + the not-before date/time listed in the "nbf" claim. Implementers MAY + provide for some small leeway, usually no more than a few minutes, to + account for clock skew. Its value MUST be a number containing a + NumericDate value. Use of this claim is OPTIONAL. + """ + if 'nbf' in self: + nbf = self['nbf'] + if not _validate_numeric_time(nbf): + raise InvalidClaimError('nbf') + if nbf > (now + leeway): + raise InvalidTokenError() + + def validate_iat(self, now, leeway): + """The "iat" (issued at) claim identifies the time at which the JWT was + issued. This claim can be used to determine the age of the JWT. + Implementers MAY provide for some small leeway, usually no more + than a few minutes, to account for clock skew. Its value MUST be a + number containing a NumericDate value. Use of this claim is OPTIONAL. + """ + if 'iat' in self: + iat = self['iat'] + if not _validate_numeric_time(iat): + raise InvalidClaimError('iat') + if iat > (now + leeway): + raise InvalidTokenError( + description='The token is not valid as it was issued in the future' + ) + + def validate_jti(self): + """The "jti" (JWT ID) claim provides a unique identifier for the JWT. + The identifier value MUST be assigned in a manner that ensures that + there is a negligible probability that the same value will be + accidentally assigned to a different data object; if the application + uses multiple issuers, collisions MUST be prevented among values + produced by different issuers as well. The "jti" claim can be used + to prevent the JWT from being replayed. The "jti" value is a case- + sensitive string. Use of this claim is OPTIONAL. + """ + self._validate_claim_value('jti') + + +def _validate_numeric_time(s): + return isinstance(s, (int, float)) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7519/jwt.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7519/jwt.py new file mode 100644 index 0000000000000000000000000000000000000000..ba27998be35e2a581cb271c566b1c3fceeca886b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc7519/jwt.py @@ -0,0 +1,183 @@ +import re +import random +import datetime +import calendar +from authlib.common.encoding import ( + to_bytes, to_unicode, + json_loads, json_dumps, +) +from .claims import JWTClaims +from ..errors import DecodeError, InsecureClaimError +from ..rfc7515 import JsonWebSignature +from ..rfc7516 import JsonWebEncryption +from ..rfc7517 import KeySet, Key + + +class JsonWebToken: + SENSITIVE_NAMES = ('password', 'token', 'secret', 'secret_key') + # Thanks to sentry SensitiveDataFilter + SENSITIVE_VALUES = re.compile(r'|'.join([ + # http://www.richardsramblings.com/regex/credit-card-numbers/ + r'\b(?:3[47]\d|(?:4\d|5[1-5]|65)\d{2}|6011)\d{12}\b', + # various private keys + r'-----BEGIN[A-Z ]+PRIVATE KEY-----.+-----END[A-Z ]+PRIVATE KEY-----', + # social security numbers (US) + r'^\b(?!(000|666|9))\d{3}-(?!00)\d{2}-(?!0000)\d{4}\b', + ]), re.DOTALL) + + def __init__(self, algorithms, private_headers=None): + self._jws = JsonWebSignature(algorithms, private_headers=private_headers) + self._jwe = JsonWebEncryption(algorithms, private_headers=private_headers) + + def check_sensitive_data(self, payload): + """Check if payload contains sensitive information.""" + for k in payload: + # check claims key name + if k in self.SENSITIVE_NAMES: + raise InsecureClaimError(k) + + # check claims values + v = payload[k] + if isinstance(v, str) and self.SENSITIVE_VALUES.search(v): + raise InsecureClaimError(k) + + def encode(self, header, payload, key, check=True): + """Encode a JWT with the given header, payload and key. + + :param header: A dict of JWS header + :param payload: A dict to be encoded + :param key: key used to sign the signature + :param check: check if sensitive data in payload + :return: bytes + """ + header.setdefault('typ', 'JWT') + + for k in ['exp', 'iat', 'nbf']: + # convert datetime into timestamp + claim = payload.get(k) + if isinstance(claim, datetime.datetime): + payload[k] = calendar.timegm(claim.utctimetuple()) + + if check: + self.check_sensitive_data(payload) + + key = find_encode_key(key, header) + text = to_bytes(json_dumps(payload)) + if 'enc' in header: + return self._jwe.serialize_compact(header, text, key) + else: + return self._jws.serialize_compact(header, text, key) + + def decode(self, s, key, claims_cls=None, + claims_options=None, claims_params=None): + """Decode the JWT with the given key. This is similar with + :meth:`verify`, except that it will raise BadSignatureError when + signature doesn't match. + + :param s: text of JWT + :param key: key used to verify the signature + :param claims_cls: class to be used for JWT claims + :param claims_options: `options` parameters for claims_cls + :param claims_params: `params` parameters for claims_cls + :return: claims_cls instance + :raise: BadSignatureError + """ + if claims_cls is None: + claims_cls = JWTClaims + + if callable(key): + load_key = key + else: + load_key = create_load_key(prepare_raw_key(key)) + + s = to_bytes(s) + dot_count = s.count(b'.') + if dot_count == 2: + data = self._jws.deserialize_compact(s, load_key, decode_payload) + elif dot_count == 4: + data = self._jwe.deserialize_compact(s, load_key, decode_payload) + else: + raise DecodeError('Invalid input segments length') + return claims_cls( + data['payload'], data['header'], + options=claims_options, + params=claims_params, + ) + + +def decode_payload(bytes_payload): + try: + payload = json_loads(to_unicode(bytes_payload)) + except ValueError: + raise DecodeError('Invalid payload value') + if not isinstance(payload, dict): + raise DecodeError('Invalid payload type') + return payload + + +def prepare_raw_key(raw): + if isinstance(raw, KeySet): + return raw + + if isinstance(raw, str) and \ + raw.startswith('{') and raw.endswith('}'): + raw = json_loads(raw) + elif isinstance(raw, (tuple, list)): + raw = {'keys': raw} + return raw + + +def find_encode_key(key, header): + if isinstance(key, KeySet): + kid = header.get('kid') + if kid: + return key.find_by_kid(kid) + + rv = random.choice(key.keys) + # use side effect to add kid value into header + header['kid'] = rv.kid + return rv + + if isinstance(key, dict) and 'keys' in key: + keys = key['keys'] + kid = header.get('kid') + for k in keys: + if k.get('kid') == kid: + return k + + if not kid: + rv = random.choice(keys) + header['kid'] = rv['kid'] + return rv + raise ValueError('Invalid JSON Web Key Set') + + # append kid into header + if isinstance(key, dict) and 'kid' in key: + header['kid'] = key['kid'] + elif isinstance(key, Key) and key.kid: + header['kid'] = key.kid + return key + + +def create_load_key(key): + def load_key(header, payload): + if isinstance(key, KeySet): + return key.find_by_kid(header.get('kid')) + + if isinstance(key, dict) and 'keys' in key: + keys = key['keys'] + kid = header.get('kid') + + if kid is not None: + # look for the requested key + for k in keys: + if k.get('kid') == kid: + return k + else: + # use the only key + if len(keys) == 1: + return keys[0] + raise ValueError('Invalid JSON Web Key Set') + return key + + return load_key diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc8037/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc8037/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fd0f3fe43bdfa9ec956cb9a28cc4bc06501a6f24 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc8037/__init__.py @@ -0,0 +1,5 @@ +from .okp_key import OKPKey +from .jws_eddsa import register_jws_rfc8037 + + +__all__ = ['register_jws_rfc8037', 'OKPKey'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc8037/jws_eddsa.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc8037/jws_eddsa.py new file mode 100644 index 0000000000000000000000000000000000000000..872da8e3c78d98127881b06244695aa0630de3e2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc8037/jws_eddsa.py @@ -0,0 +1,27 @@ +from cryptography.exceptions import InvalidSignature +from ..rfc7515 import JWSAlgorithm +from .okp_key import OKPKey + + +class EdDSAAlgorithm(JWSAlgorithm): + name = 'EdDSA' + description = 'Edwards-curve Digital Signature Algorithm for JWS' + + def prepare_key(self, raw_data): + return OKPKey.import_key(raw_data) + + def sign(self, msg, key): + op_key = key.get_op_key('sign') + return op_key.sign(msg) + + def verify(self, msg, sig, key): + op_key = key.get_op_key('verify') + try: + op_key.verify(sig, msg) + return True + except InvalidSignature: + return False + + +def register_jws_rfc8037(cls): + cls.register_algorithm(EdDSAAlgorithm()) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc8037/okp_key.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc8037/okp_key.py new file mode 100644 index 0000000000000000000000000000000000000000..40f746899d2514e3811e916ff1e83eaf12684169 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/rfc8037/okp_key.py @@ -0,0 +1,103 @@ +from cryptography.hazmat.primitives.asymmetric.ed25519 import ( + Ed25519PublicKey, Ed25519PrivateKey +) +from cryptography.hazmat.primitives.asymmetric.ed448 import ( + Ed448PublicKey, Ed448PrivateKey +) +from cryptography.hazmat.primitives.asymmetric.x25519 import ( + X25519PublicKey, X25519PrivateKey +) +from cryptography.hazmat.primitives.asymmetric.x448 import ( + X448PublicKey, X448PrivateKey +) +from cryptography.hazmat.primitives.serialization import ( + Encoding, PublicFormat, PrivateFormat, NoEncryption +) +from authlib.common.encoding import ( + to_unicode, to_bytes, + urlsafe_b64decode, urlsafe_b64encode, +) +from ..rfc7517 import AsymmetricKey + + +PUBLIC_KEYS_MAP = { + 'Ed25519': Ed25519PublicKey, + 'Ed448': Ed448PublicKey, + 'X25519': X25519PublicKey, + 'X448': X448PublicKey, +} +PRIVATE_KEYS_MAP = { + 'Ed25519': Ed25519PrivateKey, + 'Ed448': Ed448PrivateKey, + 'X25519': X25519PrivateKey, + 'X448': X448PrivateKey, +} + + +class OKPKey(AsymmetricKey): + """Key class of the ``OKP`` key type.""" + + kty = 'OKP' + REQUIRED_JSON_FIELDS = ['crv', 'x'] + PUBLIC_KEY_FIELDS = REQUIRED_JSON_FIELDS + PRIVATE_KEY_FIELDS = ['crv', 'd'] + PUBLIC_KEY_CLS = tuple(PUBLIC_KEYS_MAP.values()) + PRIVATE_KEY_CLS = tuple(PRIVATE_KEYS_MAP.values()) + SSH_PUBLIC_PREFIX = b'ssh-ed25519' + + def exchange_shared_key(self, pubkey): + # used in ECDHESAlgorithm + private_key = self.get_private_key() + if private_key and isinstance(private_key, (X25519PrivateKey, X448PrivateKey)): + return private_key.exchange(pubkey) + raise ValueError('Invalid key for exchanging shared key') + + @staticmethod + def get_key_curve(key): + if isinstance(key, (Ed25519PublicKey, Ed25519PrivateKey)): + return 'Ed25519' + elif isinstance(key, (Ed448PublicKey, Ed448PrivateKey)): + return 'Ed448' + elif isinstance(key, (X25519PublicKey, X25519PrivateKey)): + return 'X25519' + elif isinstance(key, (X448PublicKey, X448PrivateKey)): + return 'X448' + + def load_private_key(self): + crv_key = PRIVATE_KEYS_MAP[self._dict_data['crv']] + d_bytes = urlsafe_b64decode(to_bytes(self._dict_data['d'])) + return crv_key.from_private_bytes(d_bytes) + + def load_public_key(self): + crv_key = PUBLIC_KEYS_MAP[self._dict_data['crv']] + x_bytes = urlsafe_b64decode(to_bytes(self._dict_data['x'])) + return crv_key.from_public_bytes(x_bytes) + + def dumps_private_key(self): + obj = self.dumps_public_key(self.private_key.public_key()) + d_bytes = self.private_key.private_bytes( + Encoding.Raw, + PrivateFormat.Raw, + NoEncryption() + ) + obj['d'] = to_unicode(urlsafe_b64encode(d_bytes)) + return obj + + def dumps_public_key(self, public_key=None): + if public_key is None: + public_key = self.public_key + x_bytes = public_key.public_bytes(Encoding.Raw, PublicFormat.Raw) + return { + 'crv': self.get_key_curve(public_key), + 'x': to_unicode(urlsafe_b64encode(x_bytes)), + } + + @classmethod + def generate_key(cls, crv='Ed25519', options=None, is_private=False) -> 'OKPKey': + if crv not in PRIVATE_KEYS_MAP: + raise ValueError(f'Invalid crv value: "{crv}"') + private_key_cls = PRIVATE_KEYS_MAP[crv] + raw_key = private_key_cls.generate() + if not is_private: + raw_key = raw_key.public_key() + return cls.import_key(raw_key, options=options) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/util.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/util.py new file mode 100644 index 0000000000000000000000000000000000000000..5b0c759f87319f25fe402149121c58b3c6f5f961 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/jose/util.py @@ -0,0 +1,37 @@ +import binascii +from authlib.common.encoding import urlsafe_b64decode, json_loads, to_unicode +from authlib.jose.errors import DecodeError + + +def extract_header(header_segment, error_cls): + header_data = extract_segment(header_segment, error_cls, 'header') + + try: + header = json_loads(header_data.decode('utf-8')) + except ValueError as e: + raise error_cls(f'Invalid header string: {e}') + + if not isinstance(header, dict): + raise error_cls('Header must be a json object') + return header + + +def extract_segment(segment, error_cls, name='payload'): + try: + return urlsafe_b64decode(segment) + except (TypeError, binascii.Error): + msg = f'Invalid {name} padding' + raise error_cls(msg) + + +def ensure_dict(s, structure_name): + if not isinstance(s, dict): + try: + s = json_loads(to_unicode(s)) + except (ValueError, TypeError): + raise DecodeError(f'Invalid {structure_name}') + + if not isinstance(s, dict): + raise DecodeError(f'Invalid {structure_name}') + + return s diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a73ddf6b7a95d17576bae0ee3d596b3b056af0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/__init__.py @@ -0,0 +1,34 @@ +from .rfc5849 import ( + OAuth1Request, + ClientAuth, + SIGNATURE_HMAC_SHA1, + SIGNATURE_RSA_SHA1, + SIGNATURE_PLAINTEXT, + SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY, + SIGNATURE_TYPE_BODY, + ClientMixin, + TemporaryCredentialMixin, + TokenCredentialMixin, + TemporaryCredential, + AuthorizationServer, + ResourceProtector, +) + +__all__ = [ + 'OAuth1Request', + 'ClientAuth', + 'SIGNATURE_HMAC_SHA1', + 'SIGNATURE_RSA_SHA1', + 'SIGNATURE_PLAINTEXT', + 'SIGNATURE_TYPE_HEADER', + 'SIGNATURE_TYPE_QUERY', + 'SIGNATURE_TYPE_BODY', + + 'ClientMixin', + 'TemporaryCredentialMixin', + 'TokenCredentialMixin', + 'TemporaryCredential', + 'AuthorizationServer', + 'ResourceProtector', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/client.py new file mode 100644 index 0000000000000000000000000000000000000000..1f74f321adddaea318e61ee6b0329c8ead963ec6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/client.py @@ -0,0 +1,172 @@ +from authlib.common.urls import ( + url_decode, + add_params_to_uri, + urlparse, +) +from authlib.common.encoding import json_loads +from .rfc5849 import ( + SIGNATURE_HMAC_SHA1, + SIGNATURE_TYPE_HEADER, + ClientAuth, +) + + +class OAuth1Client: + auth_class = ClientAuth + + def __init__(self, session, client_id, client_secret=None, + token=None, token_secret=None, + redirect_uri=None, rsa_key=None, verifier=None, + signature_method=SIGNATURE_HMAC_SHA1, + signature_type=SIGNATURE_TYPE_HEADER, + force_include_body=False, realm=None, **kwargs): + if not client_id: + raise ValueError('Missing "client_id"') + + self.session = session + self.auth = self.auth_class( + client_id, client_secret=client_secret, + token=token, token_secret=token_secret, + redirect_uri=redirect_uri, + signature_method=signature_method, + signature_type=signature_type, + rsa_key=rsa_key, + verifier=verifier, + realm=realm, + force_include_body=force_include_body + ) + self._kwargs = kwargs + + @property + def redirect_uri(self): + return self.auth.redirect_uri + + @redirect_uri.setter + def redirect_uri(self, uri): + self.auth.redirect_uri = uri + + @property + def token(self): + return dict( + oauth_token=self.auth.token, + oauth_token_secret=self.auth.token_secret, + oauth_verifier=self.auth.verifier + ) + + @token.setter + def token(self, token): + """This token setter is designed for an easy integration for + OAuthClient. Make sure both OAuth1Session and OAuth2Session + have token setters. + """ + if token is None: + self.auth.token = None + self.auth.token_secret = None + self.auth.verifier = None + elif 'oauth_token' in token: + self.auth.token = token['oauth_token'] + if 'oauth_token_secret' in token: + self.auth.token_secret = token['oauth_token_secret'] + if 'oauth_verifier' in token: + self.auth.verifier = token['oauth_verifier'] + else: + message = f'oauth_token is missing: {token!r}' + self.handle_error('missing_token', message) + + def create_authorization_url(self, url, request_token=None, **kwargs): + """Create an authorization URL by appending request_token and optional + kwargs to url. + + This is the second step in the OAuth 1 workflow. The user should be + redirected to this authorization URL, grant access to you, and then + be redirected back to you. The redirection back can either be specified + during client registration or by supplying a callback URI per request. + + :param url: The authorization endpoint URL. + :param request_token: The previously obtained request token. + :param kwargs: Optional parameters to append to the URL. + :returns: The authorization URL with new parameters embedded. + """ + kwargs['oauth_token'] = request_token or self.auth.token + if self.auth.redirect_uri: + kwargs['oauth_callback'] = self.auth.redirect_uri + return add_params_to_uri(url, kwargs.items()) + + def fetch_request_token(self, url, **kwargs): + """Method for fetching an access token from the token endpoint. + + This is the first step in the OAuth 1 workflow. A request token is + obtained by making a signed post request to url. The token is then + parsed from the application/x-www-form-urlencoded response and ready + to be used to construct an authorization url. + + :param url: Request Token endpoint. + :param kwargs: Extra parameters to include for fetching token. + :return: A Request Token dict. + """ + return self._fetch_token(url, **kwargs) + + def fetch_access_token(self, url, verifier=None, **kwargs): + """Method for fetching an access token from the token endpoint. + + This is the final step in the OAuth 1 workflow. An access token is + obtained using all previously obtained credentials, including the + verifier from the authorization step. + + :param url: Access Token endpoint. + :param verifier: A verifier string to prove authorization was granted. + :param kwargs: Extra parameters to include for fetching access token. + :return: A token dict. + """ + if verifier: + self.auth.verifier = verifier + if not self.auth.verifier: + self.handle_error('missing_verifier', 'Missing "verifier" value') + return self._fetch_token(url, **kwargs) + + def parse_authorization_response(self, url): + """Extract parameters from the post authorization redirect + response URL. + + :param url: The full URL that resulted from the user being redirected + back from the OAuth provider to you, the client. + :returns: A dict of parameters extracted from the URL. + """ + token = dict(url_decode(urlparse.urlparse(url).query)) + self.token = token + return token + + def _fetch_token(self, url, **kwargs): + resp = self.session.post(url, auth=self.auth, **kwargs) + token = self.parse_response_token(resp.status_code, resp.text) + self.token = token + self.auth.verifier = None + return token + + def parse_response_token(self, status_code, text): + if status_code >= 400: + message = ( + "Token request failed with code {}, " + "response was '{}'." + ).format(status_code, text) + self.handle_error('fetch_token_denied', message) + + try: + text = text.strip() + if text.startswith('{'): + token = json_loads(text) + else: + token = dict(url_decode(text)) + except (TypeError, ValueError) as e: + error = ( + "Unable to decode token from token response. " + "This is commonly caused by an unsuccessful request where" + " a non urlencoded error message is returned. " + "The decoding error was {}" + ).format(e) + raise ValueError(error) + return token + + @staticmethod + def handle_error(error_type, error_description): + raise ValueError(f'{error_type}: {error_description}') diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/errors.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..e7770da53abbbf1b17eb3e4a7ec8b045067698af --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/errors.py @@ -0,0 +1,3 @@ +# flake8: noqa + +from .rfc5849.errors import * diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1f029fbbe6286bce8cf51f2d1be9ca3aecd1f9a9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/__init__.py @@ -0,0 +1,45 @@ +""" + authlib.oauth1.rfc5849 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of The OAuth 1.0 Protocol. + + https://tools.ietf.org/html/rfc5849 +""" + +from .wrapper import OAuth1Request +from .client_auth import ClientAuth +from .signature import ( + SIGNATURE_HMAC_SHA1, + SIGNATURE_RSA_SHA1, + SIGNATURE_PLAINTEXT, + SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY, + SIGNATURE_TYPE_BODY, +) +from .models import ( + ClientMixin, + TemporaryCredentialMixin, + TokenCredentialMixin, + TemporaryCredential, +) +from .authorization_server import AuthorizationServer +from .resource_protector import ResourceProtector + +__all__ = [ + 'OAuth1Request', + 'ClientAuth', + 'SIGNATURE_HMAC_SHA1', + 'SIGNATURE_RSA_SHA1', + 'SIGNATURE_PLAINTEXT', + 'SIGNATURE_TYPE_HEADER', + 'SIGNATURE_TYPE_QUERY', + 'SIGNATURE_TYPE_BODY', + + 'ClientMixin', + 'TemporaryCredentialMixin', + 'TokenCredentialMixin', + 'TemporaryCredential', + 'AuthorizationServer', + 'ResourceProtector', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/authorization_server.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/authorization_server.py new file mode 100644 index 0000000000000000000000000000000000000000..54cf7bab525e1084e1ce61127ae953edfbdc9fea --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/authorization_server.py @@ -0,0 +1,357 @@ +from authlib.common.urls import is_valid_url, add_params_to_uri +from .base_server import BaseServer +from .errors import ( + OAuth1Error, + InvalidRequestError, + MissingRequiredParameterError, + InvalidClientError, + InvalidTokenError, + AccessDeniedError, + MethodNotAllowedError, +) + + +class AuthorizationServer(BaseServer): + TOKEN_RESPONSE_HEADER = [ + ('Content-Type', 'application/x-www-form-urlencoded'), + ('Cache-Control', 'no-store'), + ('Pragma', 'no-cache'), + ] + + TEMPORARY_CREDENTIALS_METHOD = 'POST' + + def _get_client(self, request): + client = self.get_client_by_id(request.client_id) + request.client = client + return client + + def create_oauth1_request(self, request): + raise NotImplementedError() + + def handle_response(self, status_code, payload, headers): + raise NotImplementedError() + + def handle_error_response(self, error): + return self.handle_response( + error.status_code, + error.get_body(), + error.get_headers() + ) + + def validate_temporary_credentials_request(self, request): + """Validate HTTP request for temporary credentials.""" + + # The client obtains a set of temporary credentials from the server by + # making an authenticated (Section 3) HTTP "POST" request to the + # Temporary Credential Request endpoint (unless the server advertises + # another HTTP request method for the client to use). + if request.method.upper() != self.TEMPORARY_CREDENTIALS_METHOD: + raise MethodNotAllowedError() + + # REQUIRED parameter + if not request.client_id: + raise MissingRequiredParameterError('oauth_consumer_key') + + # REQUIRED parameter + oauth_callback = request.redirect_uri + if not request.redirect_uri: + raise MissingRequiredParameterError('oauth_callback') + + # An absolute URI or + # other means (the parameter value MUST be set to "oob" + if oauth_callback != 'oob' and not is_valid_url(oauth_callback): + raise InvalidRequestError('Invalid "oauth_callback" value') + + client = self._get_client(request) + if not client: + raise InvalidClientError() + + self.validate_timestamp_and_nonce(request) + self.validate_oauth_signature(request) + return request + + def create_temporary_credentials_response(self, request=None): + """Validate temporary credentials token request and create response + for temporary credentials token. Assume the endpoint of temporary + credentials request is ``https://photos.example.net/initiate``: + + .. code-block:: http + + POST /initiate HTTP/1.1 + Host: photos.example.net + Authorization: OAuth realm="Photos", + oauth_consumer_key="dpf43f3p2l4k3l03", + oauth_signature_method="HMAC-SHA1", + oauth_timestamp="137131200", + oauth_nonce="wIjqoS", + oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready", + oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D" + + The server validates the request and replies with a set of temporary + credentials in the body of the HTTP response: + + .. code-block:: http + + HTTP/1.1 200 OK + Content-Type: application/x-www-form-urlencoded + + oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03& + oauth_callback_confirmed=true + + :param request: OAuth1Request instance. + :returns: (status_code, body, headers) + """ + try: + request = self.create_oauth1_request(request) + self.validate_temporary_credentials_request(request) + except OAuth1Error as error: + return self.handle_error_response(error) + + credential = self.create_temporary_credential(request) + payload = [ + ('oauth_token', credential.get_oauth_token()), + ('oauth_token_secret', credential.get_oauth_token_secret()), + ('oauth_callback_confirmed', True) + ] + return self.handle_response(200, payload, self.TOKEN_RESPONSE_HEADER) + + def validate_authorization_request(self, request): + """Validate the request for resource owner authorization.""" + if not request.token: + raise MissingRequiredParameterError('oauth_token') + + credential = self.get_temporary_credential(request) + if not credential: + raise InvalidTokenError() + + # assign credential for later use + request.credential = credential + return request + + def create_authorization_response(self, request, grant_user=None): + """Validate authorization request and create authorization response. + Assume the endpoint for authorization request is + ``https://photos.example.net/authorize``, the client redirects Jane's + user-agent to the server's Resource Owner Authorization endpoint to + obtain Jane's approval for accessing her private photos:: + + https://photos.example.net/authorize?oauth_token=hh5s93j4hdidpola + + The server requests Jane to sign in using her username and password + and if successful, asks her to approve granting 'printer.example.com' + access to her private photos. Jane approves the request and her + user-agent is redirected to the callback URI provided by the client + in the previous request (line breaks are for display purposes only):: + + http://printer.example.com/ready? + oauth_token=hh5s93j4hdidpola&oauth_verifier=hfdp7dh39dks9884 + + :param request: OAuth1Request instance. + :param grant_user: if granted, pass the grant user, otherwise None. + :returns: (status_code, body, headers) + """ + request = self.create_oauth1_request(request) + # authorize endpoint should try catch this error + self.validate_authorization_request(request) + + temporary_credentials = request.credential + redirect_uri = temporary_credentials.get_redirect_uri() + if not redirect_uri or redirect_uri == 'oob': + client_id = temporary_credentials.get_client_id() + client = self.get_client_by_id(client_id) + redirect_uri = client.get_default_redirect_uri() + + if grant_user is None: + error = AccessDeniedError() + location = add_params_to_uri(redirect_uri, error.get_body()) + return self.handle_response(302, '', [('Location', location)]) + + request.user = grant_user + verifier = self.create_authorization_verifier(request) + + params = [ + ('oauth_token', request.token), + ('oauth_verifier', verifier) + ] + location = add_params_to_uri(redirect_uri, params) + return self.handle_response(302, '', [('Location', location)]) + + def validate_token_request(self, request): + """Validate request for issuing token.""" + + if not request.client_id: + raise MissingRequiredParameterError('oauth_consumer_key') + + client = self._get_client(request) + if not client: + raise InvalidClientError() + + if not request.token: + raise MissingRequiredParameterError('oauth_token') + + token = self.get_temporary_credential(request) + if not token: + raise InvalidTokenError() + + verifier = request.oauth_params.get('oauth_verifier') + if not verifier: + raise MissingRequiredParameterError('oauth_verifier') + + if not token.check_verifier(verifier): + raise InvalidRequestError('Invalid "oauth_verifier"') + + request.credential = token + self.validate_timestamp_and_nonce(request) + self.validate_oauth_signature(request) + return request + + def create_token_response(self, request): + """Validate token request and create token response. Assuming the + endpoint of token request is ``https://photos.example.net/token``, + the callback request informs the client that Jane completed the + authorization process. The client then requests a set of token + credentials using its temporary credentials (over a secure Transport + Layer Security (TLS) channel): + + .. code-block:: http + + POST /token HTTP/1.1 + Host: photos.example.net + Authorization: OAuth realm="Photos", + oauth_consumer_key="dpf43f3p2l4k3l03", + oauth_token="hh5s93j4hdidpola", + oauth_signature_method="HMAC-SHA1", + oauth_timestamp="137131201", + oauth_nonce="walatlh", + oauth_verifier="hfdp7dh39dks9884", + oauth_signature="gKgrFCywp7rO0OXSjdot%2FIHF7IU%3D" + + The server validates the request and replies with a set of token + credentials in the body of the HTTP response: + + .. code-block:: http + + HTTP/1.1 200 OK + Content-Type: application/x-www-form-urlencoded + + oauth_token=nnch734d00sl2jdk&oauth_token_secret=pfkkdhi9sl3r4s00 + + :param request: OAuth1Request instance. + :returns: (status_code, body, headers) + """ + try: + request = self.create_oauth1_request(request) + except OAuth1Error as error: + return self.handle_error_response(error) + + try: + self.validate_token_request(request) + except OAuth1Error as error: + self.delete_temporary_credential(request) + return self.handle_error_response(error) + + credential = self.create_token_credential(request) + payload = [ + ('oauth_token', credential.get_oauth_token()), + ('oauth_token_secret', credential.get_oauth_token_secret()), + ] + self.delete_temporary_credential(request) + return self.handle_response(200, payload, self.TOKEN_RESPONSE_HEADER) + + def create_temporary_credential(self, request): + """Generate and save a temporary credential into database or cache. + A temporary credential is used for exchanging token credential. This + method should be re-implemented:: + + def create_temporary_credential(self, request): + oauth_token = generate_token(36) + oauth_token_secret = generate_token(48) + temporary_credential = TemporaryCredential( + oauth_token=oauth_token, + oauth_token_secret=oauth_token_secret, + client_id=request.client_id, + redirect_uri=request.redirect_uri, + ) + # if the credential has a save method + temporary_credential.save() + return temporary_credential + + :param request: OAuth1Request instance + :return: TemporaryCredential instance + """ + raise NotImplementedError() + + def get_temporary_credential(self, request): + """Get the temporary credential from database or cache. A temporary + credential should share the same methods as described in models of + ``TemporaryCredentialMixin``:: + + def get_temporary_credential(self, request): + key = 'a-key-prefix:{}'.format(request.token) + data = cache.get(key) + # TemporaryCredential shares methods from TemporaryCredentialMixin + return TemporaryCredential(data) + + :param request: OAuth1Request instance + :return: TemporaryCredential instance + """ + raise NotImplementedError() + + def delete_temporary_credential(self, request): + """Delete temporary credential from database or cache. For instance, + if temporary credential is saved in cache:: + + def delete_temporary_credential(self, request): + key = 'a-key-prefix:{}'.format(request.token) + cache.delete(key) + + :param request: OAuth1Request instance + """ + raise NotImplementedError() + + def create_authorization_verifier(self, request): + """Create and bind ``oauth_verifier`` to temporary credential. It + could be re-implemented in this way:: + + def create_authorization_verifier(self, request): + verifier = generate_token(36) + + temporary_credential = request.credential + user_id = request.user.id + + temporary_credential.user_id = user_id + temporary_credential.oauth_verifier = verifier + # if the credential has a save method + temporary_credential.save() + + # remember to return the verifier + return verifier + + :param request: OAuth1Request instance + :return: A string of ``oauth_verifier`` + """ + raise NotImplementedError() + + def create_token_credential(self, request): + """Create and save token credential into database. This method would + be re-implemented like this:: + + def create_token_credential(self, request): + oauth_token = generate_token(36) + oauth_token_secret = generate_token(48) + temporary_credential = request.credential + + token_credential = TokenCredential( + oauth_token=oauth_token, + oauth_token_secret=oauth_token_secret, + client_id=temporary_credential.get_client_id(), + user_id=temporary_credential.get_user_id() + ) + # if the credential has a save method + token_credential.save() + return token_credential + + :param request: OAuth1Request instance + :return: TokenCredential instance + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/base_server.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/base_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5d29deb901f1e8a62242342d997db685157b9173 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/base_server.py @@ -0,0 +1,119 @@ +import time +from .signature import ( + SIGNATURE_HMAC_SHA1, + SIGNATURE_PLAINTEXT, + SIGNATURE_RSA_SHA1, +) +from .signature import ( + verify_hmac_sha1, + verify_plaintext, + verify_rsa_sha1, +) +from .errors import ( + InvalidRequestError, + MissingRequiredParameterError, + UnsupportedSignatureMethodError, + InvalidNonceError, + InvalidSignatureError, +) + + +class BaseServer: + SIGNATURE_METHODS = { + SIGNATURE_HMAC_SHA1: verify_hmac_sha1, + SIGNATURE_RSA_SHA1: verify_rsa_sha1, + SIGNATURE_PLAINTEXT: verify_plaintext, + } + SUPPORTED_SIGNATURE_METHODS = [SIGNATURE_HMAC_SHA1] + EXPIRY_TIME = 300 + + @classmethod + def register_signature_method(cls, name, verify): + """Extend signature method verification. + + :param name: A string to represent signature method. + :param verify: A function to verify signature. + + The ``verify`` method accept ``OAuth1Request`` as parameter:: + + def verify_custom_method(request): + # verify this request, return True or False + return True + + Server.register_signature_method('custom-name', verify_custom_method) + """ + cls.SIGNATURE_METHODS[name] = verify + + def validate_timestamp_and_nonce(self, request): + """Validate ``oauth_timestamp`` and ``oauth_nonce`` in HTTP request. + + :param request: OAuth1Request instance + """ + timestamp = request.oauth_params.get('oauth_timestamp') + nonce = request.oauth_params.get('oauth_nonce') + + if request.signature_method == SIGNATURE_PLAINTEXT: + # The parameters MAY be omitted when using the "PLAINTEXT" + # signature method + if not timestamp and not nonce: + return + + if not timestamp: + raise MissingRequiredParameterError('oauth_timestamp') + + try: + # The timestamp value MUST be a positive integer + timestamp = int(timestamp) + if timestamp < 0: + raise InvalidRequestError('Invalid "oauth_timestamp" value') + + if self.EXPIRY_TIME and time.time() - timestamp > self.EXPIRY_TIME: + raise InvalidRequestError('Invalid "oauth_timestamp" value') + except (ValueError, TypeError): + raise InvalidRequestError('Invalid "oauth_timestamp" value') + + if not nonce: + raise MissingRequiredParameterError('oauth_nonce') + + if self.exists_nonce(nonce, request): + raise InvalidNonceError() + + def validate_oauth_signature(self, request): + """Validate ``oauth_signature`` from HTTP request. + + :param request: OAuth1Request instance + """ + method = request.signature_method + if not method: + raise MissingRequiredParameterError('oauth_signature_method') + + if method not in self.SUPPORTED_SIGNATURE_METHODS: + raise UnsupportedSignatureMethodError() + + if not request.signature: + raise MissingRequiredParameterError('oauth_signature') + + verify = self.SIGNATURE_METHODS.get(method) + if not verify: + raise UnsupportedSignatureMethodError() + + if not verify(request): + raise InvalidSignatureError() + + def get_client_by_id(self, client_id): + """Get client instance with the given ``client_id``. + + :param client_id: A string of client_id + :return: Client instance + """ + raise NotImplementedError() + + def exists_nonce(self, nonce, request): + """The nonce value MUST be unique across all requests with the same + timestamp, client credentials, and token combinations. + + :param nonce: A string value of ``oauth_nonce`` + :param request: OAuth1Request instance + :return: Boolean + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/client_auth.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/client_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..2c59b5948b70571ecadea7e54897c48479589d0c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/client_auth.py @@ -0,0 +1,187 @@ +import time +import base64 +import hashlib +from authlib.common.security import generate_token +from authlib.common.urls import extract_params +from authlib.common.encoding import to_native +from .wrapper import OAuth1Request +from .signature import ( + SIGNATURE_HMAC_SHA1, + SIGNATURE_PLAINTEXT, + SIGNATURE_RSA_SHA1, + SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_BODY, + SIGNATURE_TYPE_QUERY, +) +from .signature import ( + sign_hmac_sha1, + sign_rsa_sha1, + sign_plaintext +) +from .parameters import ( + prepare_form_encoded_body, + prepare_headers, + prepare_request_uri_query, +) + + +CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded' +CONTENT_TYPE_MULTI_PART = 'multipart/form-data' + + +class ClientAuth: + SIGNATURE_METHODS = { + SIGNATURE_HMAC_SHA1: sign_hmac_sha1, + SIGNATURE_RSA_SHA1: sign_rsa_sha1, + SIGNATURE_PLAINTEXT: sign_plaintext, + } + + @classmethod + def register_signature_method(cls, name, sign): + """Extend client signature methods. + + :param name: A string to represent signature method. + :param sign: A function to generate signature. + + The ``sign`` method accept 2 parameters:: + + def custom_sign_method(client, request): + # client is the instance of Client. + return 'your-signed-string' + + Client.register_signature_method('custom-name', custom_sign_method) + """ + cls.SIGNATURE_METHODS[name] = sign + + def __init__(self, client_id, client_secret=None, + token=None, token_secret=None, + redirect_uri=None, rsa_key=None, verifier=None, + signature_method=SIGNATURE_HMAC_SHA1, + signature_type=SIGNATURE_TYPE_HEADER, + realm=None, force_include_body=False): + self.client_id = client_id + self.client_secret = client_secret + self.token = token + self.token_secret = token_secret + self.redirect_uri = redirect_uri + self.signature_method = signature_method + self.signature_type = signature_type + self.rsa_key = rsa_key + self.verifier = verifier + self.realm = realm + self.force_include_body = force_include_body + + def get_oauth_signature(self, method, uri, headers, body): + """Get an OAuth signature to be used in signing a request + + To satisfy `section 3.4.1.2`_ item 2, if the request argument's + headers dict attribute contains a Host item, its value will + replace any netloc part of the request argument's uri attribute + value. + + .. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2 + """ + sign = self.SIGNATURE_METHODS.get(self.signature_method) + if not sign: + raise ValueError('Invalid signature method.') + + request = OAuth1Request(method, uri, body=body, headers=headers) + return sign(self, request) + + def get_oauth_params(self, nonce, timestamp): + oauth_params = [ + ('oauth_nonce', nonce), + ('oauth_timestamp', timestamp), + ('oauth_version', '1.0'), + ('oauth_signature_method', self.signature_method), + ('oauth_consumer_key', self.client_id), + ] + if self.token: + oauth_params.append(('oauth_token', self.token)) + if self.redirect_uri: + oauth_params.append(('oauth_callback', self.redirect_uri)) + if self.verifier: + oauth_params.append(('oauth_verifier', self.verifier)) + return oauth_params + + def _render(self, uri, headers, body, oauth_params): + if self.signature_type == SIGNATURE_TYPE_HEADER: + headers = prepare_headers(oauth_params, headers, realm=self.realm) + elif self.signature_type == SIGNATURE_TYPE_BODY: + if CONTENT_TYPE_FORM_URLENCODED in headers.get('Content-Type', ''): + decoded_body = extract_params(body) or [] + body = prepare_form_encoded_body(oauth_params, decoded_body) + headers['Content-Type'] = CONTENT_TYPE_FORM_URLENCODED + elif self.signature_type == SIGNATURE_TYPE_QUERY: + uri = prepare_request_uri_query(oauth_params, uri) + else: + raise ValueError('Unknown signature type specified.') + return uri, headers, body + + def sign(self, method, uri, headers, body): + """Sign the HTTP request, add OAuth parameters and signature. + + :param method: HTTP method of the request. + :param uri: URI of the HTTP request. + :param body: Body payload of the HTTP request. + :param headers: Headers of the HTTP request. + :return: uri, headers, body + """ + nonce = generate_nonce() + timestamp = generate_timestamp() + if body is None: + body = b'' + + # transform int to str + timestamp = str(timestamp) + + if headers is None: + headers = {} + + oauth_params = self.get_oauth_params(nonce, timestamp) + + # https://datatracker.ietf.org/doc/html/draft-eaton-oauth-bodyhash-00.html + # include oauth_body_hash + if body and headers.get('Content-Type') != CONTENT_TYPE_FORM_URLENCODED: + oauth_body_hash = base64.b64encode(hashlib.sha1(body).digest()) + oauth_params.append(('oauth_body_hash', oauth_body_hash.decode('utf-8'))) + + uri, headers, body = self._render(uri, headers, body, oauth_params) + + sig = self.get_oauth_signature(method, uri, headers, body) + oauth_params.append(('oauth_signature', sig)) + + uri, headers, body = self._render(uri, headers, body, oauth_params) + return uri, headers, body + + def prepare(self, method, uri, headers, body): + """Add OAuth parameters to the request. + + Parameters may be included from the body if the content-type is + urlencoded, if no content type is set, a guess is made. + """ + content_type = to_native(headers.get('Content-Type', '')) + if self.signature_type == SIGNATURE_TYPE_BODY: + content_type = CONTENT_TYPE_FORM_URLENCODED + elif not content_type and extract_params(body): + content_type = CONTENT_TYPE_FORM_URLENCODED + + if CONTENT_TYPE_FORM_URLENCODED in content_type: + headers['Content-Type'] = CONTENT_TYPE_FORM_URLENCODED + uri, headers, body = self.sign(method, uri, headers, body) + elif self.force_include_body: + # To allow custom clients to work on non form encoded bodies. + uri, headers, body = self.sign(method, uri, headers, body) + else: + # Omit body data in the signing of non form-encoded requests + uri, headers, _ = self.sign(method, uri, headers, b'') + body = b'' + return uri, headers, body + + +def generate_nonce(): + return generate_token() + + +def generate_timestamp(): + return str(int(time.time())) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/errors.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..93396fcebffc2bfdc9d8456c78e538ef4babc988 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/errors.py @@ -0,0 +1,89 @@ +""" + authlib.oauth1.rfc5849.errors + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + RFC5849 has no definition on errors. This module is designed by + Authlib based on OAuth 1.0a `Section 10`_ with some changes. + + .. _`Section 10`: https://oauth.net/core/1.0a/#rfc.section.10 +""" +from authlib.common.errors import AuthlibHTTPError +from authlib.common.security import is_secure_transport + + +class OAuth1Error(AuthlibHTTPError): + def __init__(self, description=None, uri=None, status_code=None): + super().__init__(None, description, uri, status_code) + + def get_headers(self): + """Get a list of headers.""" + return [ + ('Content-Type', 'application/x-www-form-urlencoded'), + ('Cache-Control', 'no-store'), + ('Pragma', 'no-cache') + ] + + +class InsecureTransportError(OAuth1Error): + error = 'insecure_transport' + description = 'OAuth 2 MUST utilize https.' + + @classmethod + def check(cls, uri): + if not is_secure_transport(uri): + raise cls() + + +class InvalidRequestError(OAuth1Error): + error = 'invalid_request' + + +class UnsupportedParameterError(OAuth1Error): + error = 'unsupported_parameter' + + +class UnsupportedSignatureMethodError(OAuth1Error): + error = 'unsupported_signature_method' + + +class MissingRequiredParameterError(OAuth1Error): + error = 'missing_required_parameter' + + def __init__(self, key): + description = f'missing "{key}" in parameters' + super().__init__(description=description) + + +class DuplicatedOAuthProtocolParameterError(OAuth1Error): + error = 'duplicated_oauth_protocol_parameter' + + +class InvalidClientError(OAuth1Error): + error = 'invalid_client' + status_code = 401 + + +class InvalidTokenError(OAuth1Error): + error = 'invalid_token' + description = 'Invalid or expired "oauth_token" in parameters' + status_code = 401 + + +class InvalidSignatureError(OAuth1Error): + error = 'invalid_signature' + status_code = 401 + + +class InvalidNonceError(OAuth1Error): + error = 'invalid_nonce' + status_code = 401 + + +class AccessDeniedError(OAuth1Error): + error = 'access_denied' + description = 'The resource owner or authorization server denied the request' + + +class MethodNotAllowedError(OAuth1Error): + error = 'method_not_allowed' + status_code = 405 diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c9f3ea61d10b22006bc30efb7e04f85aa03cdac7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/models.py @@ -0,0 +1,108 @@ +class ClientMixin: + def get_default_redirect_uri(self): + """A method to get client default redirect_uri. For instance, the + database table for client has a column called ``default_redirect_uri``:: + + def get_default_redirect_uri(self): + return self.default_redirect_uri + + :return: A URL string + """ + raise NotImplementedError() + + def get_client_secret(self): + """A method to return the client_secret of this client. For instance, + the database table has a column called ``client_secret``:: + + def get_client_secret(self): + return self.client_secret + """ + raise NotImplementedError() + + def get_rsa_public_key(self): + """A method to get the RSA public key for RSA-SHA1 signature method. + For instance, the value is saved on column ``rsa_public_key``:: + + def get_rsa_public_key(self): + return self.rsa_public_key + """ + raise NotImplementedError() + + +class TokenCredentialMixin: + def get_oauth_token(self): + """A method to get the value of ``oauth_token``. For instance, the + database table has a column called ``oauth_token``:: + + def get_oauth_token(self): + return self.oauth_token + + :return: A string + """ + raise NotImplementedError() + + def get_oauth_token_secret(self): + """A method to get the value of ``oauth_token_secret``. For instance, + the database table has a column called ``oauth_token_secret``:: + + def get_oauth_token_secret(self): + return self.oauth_token_secret + + :return: A string + """ + raise NotImplementedError() + + +class TemporaryCredentialMixin(TokenCredentialMixin): + def get_client_id(self): + """A method to get the client_id associated with this credential. + For instance, the table in the database has a column ``client_id``:: + + def get_client_id(self): + return self.client_id + """ + raise NotImplementedError() + + def get_redirect_uri(self): + """A method to get temporary credential's ``oauth_callback``. + For instance, the database table for temporary credential has a + column called ``oauth_callback``:: + + def get_redirect_uri(self): + return self.oauth_callback + + :return: A URL string + """ + raise NotImplementedError() + + def check_verifier(self, verifier): + """A method to check if the given verifier matches this temporary + credential. For instance that this temporary credential has recorded + the value in database as column ``oauth_verifier``:: + + def check_verifier(self, verifier): + return self.oauth_verifier == verifier + + :return: Boolean + """ + raise NotImplementedError() + + +class TemporaryCredential(dict, TemporaryCredentialMixin): + def get_client_id(self): + return self.get('client_id') + + def get_user_id(self): + return self.get('user_id') + + def get_redirect_uri(self): + return self.get('oauth_callback') + + def check_verifier(self, verifier): + return self.get('oauth_verifier') == verifier + + def get_oauth_token(self): + return self.get('oauth_token') + + def get_oauth_token_secret(self): + return self.get('oauth_token_secret') diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/parameters.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..0e64e5c606a97f7c1a49f3e2d9c88ceebe8653ac --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/parameters.py @@ -0,0 +1,101 @@ +""" + authlib.spec.rfc5849.parameters + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + This module contains methods related to `section 3.5`_ of the OAuth 1.0a spec. + + .. _`section 3.5`: https://tools.ietf.org/html/rfc5849#section-3.5 +""" +from authlib.common.urls import urlparse, url_encode, extract_params +from .util import escape + + +def prepare_headers(oauth_params, headers=None, realm=None): + """**Prepare the Authorization header.** + Per `section 3.5.1`_ of the spec. + + Protocol parameters can be transmitted using the HTTP "Authorization" + header field as defined by `RFC2617`_ with the auth-scheme name set to + "OAuth" (case insensitive). + + For example:: + + Authorization: OAuth realm="Photos", + oauth_consumer_key="dpf43f3p2l4k3l03", + oauth_signature_method="HMAC-SHA1", + oauth_timestamp="137131200", + oauth_nonce="wIjqoS", + oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready", + oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D", + oauth_version="1.0" + + .. _`section 3.5.1`: https://tools.ietf.org/html/rfc5849#section-3.5.1 + .. _`RFC2617`: https://tools.ietf.org/html/rfc2617 + """ + headers = headers or {} + + # step 1, 2, 3 in Section 3.5.1 + header_parameters = ', '.join([ + f'{escape(k)}="{escape(v)}"' for k, v in oauth_params + if k.startswith('oauth_') + ]) + + # 4. The OPTIONAL "realm" parameter MAY be added and interpreted per + # `RFC2617 section 1.2`_. + # + # .. _`RFC2617 section 1.2`: https://tools.ietf.org/html/rfc2617#section-1.2 + if realm: + # NOTE: realm should *not* be escaped + header_parameters = f'realm="{realm}", ' + header_parameters + + # the auth-scheme name set to "OAuth" (case insensitive). + headers['Authorization'] = f'OAuth {header_parameters}' + return headers + + +def _append_params(oauth_params, params): + """Append OAuth params to an existing set of parameters. + + Both params and oauth_params is must be lists of 2-tuples. + + Per `section 3.5.2`_ and `3.5.3`_ of the spec. + + .. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2 + .. _`3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 + + """ + merged = list(params) + merged.extend(oauth_params) + # The request URI / entity-body MAY include other request-specific + # parameters, in which case, the protocol parameters SHOULD be appended + # following the request-specific parameters, properly separated by an "&" + # character (ASCII code 38) + merged.sort(key=lambda i: i[0].startswith('oauth_')) + return merged + + +def prepare_form_encoded_body(oauth_params, body): + """Prepare the Form-Encoded Body. + + Per `section 3.5.2`_ of the spec. + + .. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2 + + """ + # append OAuth params to the existing body + return url_encode(_append_params(oauth_params, body)) + + +def prepare_request_uri_query(oauth_params, uri): + """Prepare the Request URI Query. + + Per `section 3.5.3`_ of the spec. + + .. _`section 3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 + + """ + # append OAuth params to the existing set of query components + sch, net, path, par, query, fra = urlparse.urlparse(uri) + query = url_encode( + _append_params(oauth_params, extract_params(query) or [])) + return urlparse.urlunparse((sch, net, path, par, query, fra)) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/resource_protector.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/resource_protector.py new file mode 100644 index 0000000000000000000000000000000000000000..2b5d7819cd0b115787529c5c426e95d447b44ad1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/resource_protector.py @@ -0,0 +1,41 @@ +from .base_server import BaseServer +from .wrapper import OAuth1Request +from .errors import ( + MissingRequiredParameterError, + InvalidClientError, + InvalidTokenError, +) + + +class ResourceProtector(BaseServer): + def validate_request(self, method, uri, body, headers): + request = OAuth1Request(method, uri, body, headers) + + if not request.client_id: + raise MissingRequiredParameterError('oauth_consumer_key') + + client = self.get_client_by_id(request.client_id) + if not client: + raise InvalidClientError() + request.client = client + + if not request.token: + raise MissingRequiredParameterError('oauth_token') + + token = self.get_token_credential(request) + if not token: + raise InvalidTokenError() + + request.credential = token + self.validate_timestamp_and_nonce(request) + self.validate_oauth_signature(request) + return request + + def get_token_credential(self, request): + """Fetch the token credential from data store like a database, + framework should implement this function. + + :param request: OAuth1Request instance + :return: Token model instance + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/rsa.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/rsa.py new file mode 100644 index 0000000000000000000000000000000000000000..3785b0f7905a63aaf4f108b9afd992bdb1a840c0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/rsa.py @@ -0,0 +1,29 @@ +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.serialization import ( + load_pem_private_key, load_pem_public_key +) +from cryptography.hazmat.primitives.asymmetric import padding +from cryptography.exceptions import InvalidSignature +from authlib.common.encoding import to_bytes + + +def sign_sha1(msg, rsa_private_key): + key = load_pem_private_key( + to_bytes(rsa_private_key), + password=None, + backend=default_backend() + ) + return key.sign(msg, padding.PKCS1v15(), hashes.SHA1()) + + +def verify_sha1(sig, msg, rsa_public_key): + key = load_pem_public_key( + to_bytes(rsa_public_key), + backend=default_backend() + ) + try: + key.verify(sig, msg, padding.PKCS1v15(), hashes.SHA1()) + return True + except InvalidSignature: + return False diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/signature.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/signature.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb87fee6003ea1c608d7e192590b8f67cbb3d82 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/signature.py @@ -0,0 +1,386 @@ +""" + authlib.oauth1.rfc5849.signature + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of `section 3.4`_ of the spec. + + .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4 +""" +import binascii +import hashlib +import hmac +from authlib.common.urls import urlparse +from authlib.common.encoding import to_unicode, to_bytes +from .util import escape, unescape + +SIGNATURE_HMAC_SHA1 = "HMAC-SHA1" +SIGNATURE_RSA_SHA1 = "RSA-SHA1" +SIGNATURE_PLAINTEXT = "PLAINTEXT" + +SIGNATURE_TYPE_HEADER = 'HEADER' +SIGNATURE_TYPE_QUERY = 'QUERY' +SIGNATURE_TYPE_BODY = 'BODY' + + +def construct_base_string(method, uri, params, host=None): + """Generate signature base string from request, per `Section 3.4.1`_. + + For example, the HTTP request:: + + POST /request?b5=%3D%253D&a3=a&c%40=&a2=r%20b HTTP/1.1 + Host: example.com + Content-Type: application/x-www-form-urlencoded + Authorization: OAuth realm="Example", + oauth_consumer_key="9djdj82h48djs9d2", + oauth_token="kkk9d7dh3k39sjv7", + oauth_signature_method="HMAC-SHA1", + oauth_timestamp="137131201", + oauth_nonce="7d8f3e4a", + oauth_signature="bYT5CMsGcbgUdFHObYMEfcx6bsw%3D" + + c2&a3=2+q + + is represented by the following signature base string (line breaks + are for display purposes only):: + + POST&http%3A%2F%2Fexample.com%2Frequest&a2%3Dr%2520b%26a3%3D2%2520q + %26a3%3Da%26b5%3D%253D%25253D%26c%2540%3D%26c2%3D%26oauth_consumer_ + key%3D9djdj82h48djs9d2%26oauth_nonce%3D7d8f3e4a%26oauth_signature_m + ethod%3DHMAC-SHA1%26oauth_timestamp%3D137131201%26oauth_token%3Dkkk + 9d7dh3k39sjv7 + + .. _`Section 3.4.1`: https://tools.ietf.org/html/rfc5849#section-3.4.1 + """ + + # Create base string URI per Section 3.4.1.2 + base_string_uri = normalize_base_string_uri(uri, host) + + # Cleanup parameter sources per Section 3.4.1.3.1 + unescaped_params = [] + for k, v in params: + # The "oauth_signature" parameter MUST be excluded from the signature + if k in ('oauth_signature', 'realm'): + continue + + # ensure oauth params are unescaped + if k.startswith('oauth_'): + v = unescape(v) + unescaped_params.append((k, v)) + + # Normalize parameters per Section 3.4.1.3.2 + normalized_params = normalize_parameters(unescaped_params) + + # construct base string + return '&'.join([ + escape(method.upper()), + escape(base_string_uri), + escape(normalized_params), + ]) + + +def normalize_base_string_uri(uri, host=None): + """Normalize Base String URI per `Section 3.4.1.2`_. + + For example, the HTTP request:: + + GET /r%20v/X?id=123 HTTP/1.1 + Host: EXAMPLE.COM:80 + + is represented by the base string URI: "http://example.com/r%20v/X". + + In another example, the HTTPS request:: + + GET /?q=1 HTTP/1.1 + Host: www.example.net:8080 + + is represented by the base string URI: "https://www.example.net:8080/". + + .. _`Section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2 + + The host argument overrides the netloc part of the uri argument. + """ + uri = to_unicode(uri) + scheme, netloc, path, params, query, fragment = urlparse.urlparse(uri) + + # The scheme, authority, and path of the request resource URI `RFC3986` + # are included by constructing an "http" or "https" URI representing + # the request resource (without the query or fragment) as follows: + # + # .. _`RFC3986`: https://tools.ietf.org/html/rfc3986 + + if not scheme or not netloc: + raise ValueError('uri must include a scheme and netloc') + + # Per `RFC 2616 section 5.1.2`_: + # + # Note that the absolute path cannot be empty; if none is present in + # the original URI, it MUST be given as "/" (the server root). + # + # .. _`RFC 2616 section 5.1.2`: https://tools.ietf.org/html/rfc2616#section-5.1.2 + if not path: + path = '/' + + # 1. The scheme and host MUST be in lowercase. + scheme = scheme.lower() + netloc = netloc.lower() + + # 2. The host and port values MUST match the content of the HTTP + # request "Host" header field. + if host is not None: + netloc = host.lower() + + # 3. The port MUST be included if it is not the default port for the + # scheme, and MUST be excluded if it is the default. Specifically, + # the port MUST be excluded when making an HTTP request `RFC2616`_ + # to port 80 or when making an HTTPS request `RFC2818`_ to port 443. + # All other non-default port numbers MUST be included. + # + # .. _`RFC2616`: https://tools.ietf.org/html/rfc2616 + # .. _`RFC2818`: https://tools.ietf.org/html/rfc2818 + default_ports = ( + ('http', '80'), + ('https', '443'), + ) + if ':' in netloc: + host, port = netloc.split(':', 1) + if (scheme, port) in default_ports: + netloc = host + + return urlparse.urlunparse((scheme, netloc, path, params, '', '')) + + +def normalize_parameters(params): + """Normalize parameters per `Section 3.4.1.3.2`_. + + For example, the list of parameters from the previous section would + be normalized as follows: + + Encoded:: + + +------------------------+------------------+ + | Name | Value | + +------------------------+------------------+ + | b5 | %3D%253D | + | a3 | a | + | c%40 | | + | a2 | r%20b | + | oauth_consumer_key | 9djdj82h48djs9d2 | + | oauth_token | kkk9d7dh3k39sjv7 | + | oauth_signature_method | HMAC-SHA1 | + | oauth_timestamp | 137131201 | + | oauth_nonce | 7d8f3e4a | + | c2 | | + | a3 | 2%20q | + +------------------------+------------------+ + + Sorted:: + + +------------------------+------------------+ + | Name | Value | + +------------------------+------------------+ + | a2 | r%20b | + | a3 | 2%20q | + | a3 | a | + | b5 | %3D%253D | + | c%40 | | + | c2 | | + | oauth_consumer_key | 9djdj82h48djs9d2 | + | oauth_nonce | 7d8f3e4a | + | oauth_signature_method | HMAC-SHA1 | + | oauth_timestamp | 137131201 | + | oauth_token | kkk9d7dh3k39sjv7 | + +------------------------+------------------+ + + Concatenated Pairs:: + + +-------------------------------------+ + | Name=Value | + +-------------------------------------+ + | a2=r%20b | + | a3=2%20q | + | a3=a | + | b5=%3D%253D | + | c%40= | + | c2= | + | oauth_consumer_key=9djdj82h48djs9d2 | + | oauth_nonce=7d8f3e4a | + | oauth_signature_method=HMAC-SHA1 | + | oauth_timestamp=137131201 | + | oauth_token=kkk9d7dh3k39sjv7 | + +-------------------------------------+ + + and concatenated together into a single string (line breaks are for + display purposes only):: + + a2=r%20b&a3=2%20q&a3=a&b5=%3D%253D&c%40=&c2=&oauth_consumer_key=9dj + dj82h48djs9d2&oauth_nonce=7d8f3e4a&oauth_signature_method=HMAC-SHA1 + &oauth_timestamp=137131201&oauth_token=kkk9d7dh3k39sjv7 + + .. _`Section 3.4.1.3.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 + """ + + # 1. First, the name and value of each parameter are encoded + # (`Section 3.6`_). + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + key_values = [(escape(k), escape(v)) for k, v in params] + + # 2. The parameters are sorted by name, using ascending byte value + # ordering. If two or more parameters share the same name, they + # are sorted by their value. + key_values.sort() + + # 3. The name of each parameter is concatenated to its corresponding + # value using an "=" character (ASCII code 61) as a separator, even + # if the value is empty. + parameter_parts = [f'{k}={v}' for k, v in key_values] + + # 4. The sorted name/value pairs are concatenated together into a + # single string by using an "&" character (ASCII code 38) as + # separator. + return '&'.join(parameter_parts) + + +def generate_signature_base_string(request): + """Generate signature base string from request.""" + host = request.headers.get('Host', None) + return construct_base_string( + request.method, request.uri, request.params, host) + + +def hmac_sha1_signature(base_string, client_secret, token_secret): + """Generate signature via HMAC-SHA1 method, per `Section 3.4.2`_. + + The "HMAC-SHA1" signature method uses the HMAC-SHA1 signature + algorithm as defined in `RFC2104`_:: + + digest = HMAC-SHA1 (key, text) + + .. _`RFC2104`: https://tools.ietf.org/html/rfc2104 + .. _`Section 3.4.2`: https://tools.ietf.org/html/rfc5849#section-3.4.2 + """ + + # The HMAC-SHA1 function variables are used in following way: + + # text is set to the value of the signature base string from + # `Section 3.4.1.1`_. + # + # .. _`Section 3.4.1.1`: https://tools.ietf.org/html/rfc5849#section-3.4.1.1 + text = base_string + + # key is set to the concatenated values of: + # 1. The client shared-secret, after being encoded (`Section 3.6`_). + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + key = escape(client_secret or '') + + # 2. An "&" character (ASCII code 38), which MUST be included + # even when either secret is empty. + key += '&' + + # 3. The token shared-secret, after being encoded (`Section 3.6`_). + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + key += escape(token_secret or '') + + signature = hmac.new(to_bytes(key), to_bytes(text), hashlib.sha1) + + # digest is used to set the value of the "oauth_signature" protocol + # parameter, after the result octet string is base64-encoded + # per `RFC2045, Section 6.8`. + # + # .. _`RFC2045, Section 6.8`: https://tools.ietf.org/html/rfc2045#section-6.8 + sig = binascii.b2a_base64(signature.digest())[:-1] + return to_unicode(sig) + + +def rsa_sha1_signature(base_string, rsa_private_key): + """Generate signature via RSA-SHA1 method, per `Section 3.4.3`_. + + The "RSA-SHA1" signature method uses the RSASSA-PKCS1-v1_5 signature + algorithm as defined in `RFC3447, Section 8.2`_ (also known as + PKCS#1), using SHA-1 as the hash function for EMSA-PKCS1-v1_5. To + use this method, the client MUST have established client credentials + with the server that included its RSA public key (in a manner that is + beyond the scope of this specification). + + .. _`Section 3.4.3`: https://tools.ietf.org/html/rfc5849#section-3.4.3 + .. _`RFC3447, Section 8.2`: https://tools.ietf.org/html/rfc3447#section-8.2 + """ + from .rsa import sign_sha1 + base_string = to_bytes(base_string) + s = sign_sha1(to_bytes(base_string), rsa_private_key) + sig = binascii.b2a_base64(s)[:-1] + return to_unicode(sig) + + +def plaintext_signature(client_secret, token_secret): + """Generate signature via PLAINTEXT method, per `Section 3.4.4`_. + + The "PLAINTEXT" method does not employ a signature algorithm. It + MUST be used with a transport-layer mechanism such as TLS or SSL (or + sent over a secure channel with equivalent protections). It does not + utilize the signature base string or the "oauth_timestamp" and + "oauth_nonce" parameters. + + .. _`Section 3.4.4`: https://tools.ietf.org/html/rfc5849#section-3.4.4 + """ + + # The "oauth_signature" protocol parameter is set to the concatenated + # value of: + + # 1. The client shared-secret, after being encoded (`Section 3.6`_). + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + signature = escape(client_secret or '') + + # 2. An "&" character (ASCII code 38), which MUST be included even + # when either secret is empty. + signature += '&' + + # 3. The token shared-secret, after being encoded (`Section 3.6`_). + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + signature += escape(token_secret or '') + + return signature + + +def sign_hmac_sha1(client, request): + """Sign a HMAC-SHA1 signature.""" + base_string = generate_signature_base_string(request) + return hmac_sha1_signature( + base_string, client.client_secret, client.token_secret) + + +def sign_rsa_sha1(client, request): + """Sign a RSASSA-PKCS #1 v1.5 base64 encoded signature.""" + base_string = generate_signature_base_string(request) + return rsa_sha1_signature(base_string, client.rsa_key) + + +def sign_plaintext(client, request): + """Sign a PLAINTEXT signature.""" + return plaintext_signature(client.client_secret, client.token_secret) + + +def verify_hmac_sha1(request): + """Verify a HMAC-SHA1 signature.""" + base_string = generate_signature_base_string(request) + sig = hmac_sha1_signature( + base_string, request.client_secret, request.token_secret) + return hmac.compare_digest(sig, request.signature) + + +def verify_rsa_sha1(request): + """Verify a RSASSA-PKCS #1 v1.5 base64 encoded signature.""" + from .rsa import verify_sha1 + base_string = generate_signature_base_string(request) + sig = binascii.a2b_base64(to_bytes(request.signature)) + return verify_sha1(sig, to_bytes(base_string), request.rsa_public_key) + + +def verify_plaintext(request): + """Verify a PLAINTEXT signature.""" + sig = plaintext_signature(request.client_secret, request.token_secret) + return hmac.compare_digest(sig, request.signature) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/util.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/util.py new file mode 100644 index 0000000000000000000000000000000000000000..9383e22ed1de5f3da44662c20fb345bd687c75d4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/util.py @@ -0,0 +1,9 @@ +from authlib.common.urls import quote, unquote + + +def escape(s): + return quote(s, safe=b'~') + + +def unescape(s): + return unquote(s) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/wrapper.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..c03687ed658774c2829a19fd2448c9e2472e5125 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth1/rfc5849/wrapper.py @@ -0,0 +1,129 @@ +from urllib.request import parse_keqv_list, parse_http_list +from authlib.common.urls import ( + urlparse, extract_params, url_decode, +) +from .signature import ( + SIGNATURE_TYPE_QUERY, + SIGNATURE_TYPE_BODY, + SIGNATURE_TYPE_HEADER +) +from .errors import ( + InsecureTransportError, + DuplicatedOAuthProtocolParameterError +) +from .util import unescape + + +class OAuth1Request: + def __init__(self, method, uri, body=None, headers=None): + InsecureTransportError.check(uri) + self.method = method + self.uri = uri + self.body = body + self.headers = headers or {} + + # states namespaces + self.client = None + self.credential = None + self.user = None + + self.query = urlparse.urlparse(uri).query + self.query_params = url_decode(self.query) + self.body_params = extract_params(body) or [] + + self.auth_params, self.realm = _parse_authorization_header(headers) + self.signature_type, self.oauth_params = _parse_oauth_params( + self.query_params, self.body_params, self.auth_params) + + params = [] + params.extend(self.query_params) + params.extend(self.body_params) + params.extend(self.auth_params) + self.params = params + + @property + def client_id(self): + return self.oauth_params.get('oauth_consumer_key') + + @property + def client_secret(self): + if self.client: + return self.client.get_client_secret() + + @property + def rsa_public_key(self): + if self.client: + return self.client.get_rsa_public_key() + + @property + def timestamp(self): + return self.oauth_params.get('oauth_timestamp') + + @property + def redirect_uri(self): + return self.oauth_params.get('oauth_callback') + + @property + def signature(self): + return self.oauth_params.get('oauth_signature') + + @property + def signature_method(self): + return self.oauth_params.get('oauth_signature_method') + + @property + def token(self): + return self.oauth_params.get('oauth_token') + + @property + def token_secret(self): + if self.credential: + return self.credential.get_oauth_token_secret() + + +def _filter_oauth(params): + for k, v in params: + if k.startswith('oauth_'): + yield (k, v) + + +def _parse_authorization_header(headers): + """Parse an OAuth authorization header into a list of 2-tuples""" + authorization_header = headers.get('Authorization') + if not authorization_header: + return [], None + + auth_scheme = 'oauth ' + if authorization_header.lower().startswith(auth_scheme): + items = parse_http_list(authorization_header[len(auth_scheme):]) + try: + items = parse_keqv_list(items).items() + auth_params = [(unescape(k), unescape(v)) for k, v in items] + realm = dict(auth_params).get('realm') + return auth_params, realm + except (IndexError, ValueError): + pass + raise ValueError('Malformed authorization header') + + +def _parse_oauth_params(query_params, body_params, auth_params): + oauth_params_set = [ + (SIGNATURE_TYPE_QUERY, list(_filter_oauth(query_params))), + (SIGNATURE_TYPE_BODY, list(_filter_oauth(body_params))), + (SIGNATURE_TYPE_HEADER, list(_filter_oauth(auth_params))) + ] + oauth_params_set = [params for params in oauth_params_set if params[1]] + if len(oauth_params_set) > 1: + found_types = [p[0] for p in oauth_params_set] + raise DuplicatedOAuthProtocolParameterError( + '"oauth_" params must come from only 1 signature type ' + 'but were found in {}'.format(','.join(found_types)) + ) + + if oauth_params_set: + signature_type = oauth_params_set[0][0] + oauth_params = dict(oauth_params_set[0][1]) + else: + signature_type = None + oauth_params = {} + return signature_type, oauth_params diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..05fdf30bbb2f23ddbc5319307b415d49d55b473e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/__init__.py @@ -0,0 +1,16 @@ +from .base import OAuth2Error +from .auth import ClientAuth, TokenAuth +from .client import OAuth2Client +from .rfc6749 import ( + OAuth2Request, + JsonRequest, + AuthorizationServer, + ClientAuthentication, + ResourceProtector, +) + +__all__ = [ + 'OAuth2Error', 'ClientAuth', 'TokenAuth', 'OAuth2Client', + 'OAuth2Request', 'JsonRequest', 'AuthorizationServer', + 'ClientAuthentication', 'ResourceProtector', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/auth.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..e4ad18046b999a7c571f793b1f53cca5ca1d9178 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/auth.py @@ -0,0 +1,106 @@ +import base64 +from urllib.parse import quote +from authlib.common.urls import add_params_to_qs, add_params_to_uri +from authlib.common.encoding import to_bytes, to_native +from .rfc6749 import OAuth2Token +from .rfc6750 import add_bearer_token + + +def encode_client_secret_basic(client, method, uri, headers, body): + text = f'{quote(client.client_id)}:{quote(client.client_secret)}' + auth = to_native(base64.b64encode(to_bytes(text, 'latin1'))) + headers['Authorization'] = f'Basic {auth}' + return uri, headers, body + + +def encode_client_secret_post(client, method, uri, headers, body): + body = add_params_to_qs(body or '', [ + ('client_id', client.client_id), + ('client_secret', client.client_secret or '') + ]) + if 'Content-Length' in headers: + headers['Content-Length'] = str(len(body)) + return uri, headers, body + + +def encode_none(client, method, uri, headers, body): + if method == 'GET': + uri = add_params_to_uri(uri, [('client_id', client.client_id)]) + return uri, headers, body + body = add_params_to_qs(body, [('client_id', client.client_id)]) + if 'Content-Length' in headers: + headers['Content-Length'] = str(len(body)) + return uri, headers, body + + +class ClientAuth: + """Attaches OAuth Client Information to HTTP requests. + + :param client_id: Client ID, which you get from client registration. + :param client_secret: Client Secret, which you get from registration. + :param auth_method: Client auth method for token endpoint. The supported + methods for now: + + * client_secret_basic (default) + * client_secret_post + * none + """ + DEFAULT_AUTH_METHODS = { + 'client_secret_basic': encode_client_secret_basic, + 'client_secret_post': encode_client_secret_post, + 'none': encode_none, + } + + def __init__(self, client_id, client_secret, auth_method=None): + if auth_method is None: + auth_method = 'client_secret_basic' + + self.client_id = client_id + self.client_secret = client_secret + + if auth_method in self.DEFAULT_AUTH_METHODS: + auth_method = self.DEFAULT_AUTH_METHODS[auth_method] + + self.auth_method = auth_method + + def prepare(self, method, uri, headers, body): + return self.auth_method(self, method, uri, headers, body) + + +class TokenAuth: + """Attach token information to HTTP requests. + + :param token: A dict or OAuth2Token instance of an OAuth 2.0 token + :param token_placement: The placement of the token, default is ``header``, + available choices: + + * header (default) + * body + * uri + """ + DEFAULT_TOKEN_TYPE = 'bearer' + SIGN_METHODS = { + 'bearer': add_bearer_token + } + + def __init__(self, token, token_placement='header', client=None): + self.token = OAuth2Token.from_dict(token) + self.token_placement = token_placement + self.client = client + self.hooks = set() + + def set_token(self, token): + self.token = OAuth2Token.from_dict(token) + + def prepare(self, uri, headers, body): + token_type = self.token.get('token_type', self.DEFAULT_TOKEN_TYPE) + sign = self.SIGN_METHODS[token_type.lower()] + uri, headers, body = sign( + self.token['access_token'], + uri, headers, body, + self.token_placement) + + for hook in self.hooks: + uri, headers, body = hook(uri, headers, body) + + return uri, headers, body diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/base.py new file mode 100644 index 0000000000000000000000000000000000000000..9bcb15f888010b4f6d9b154ee3436f0eb2957905 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/base.py @@ -0,0 +1,26 @@ +from authlib.common.errors import AuthlibHTTPError +from authlib.common.urls import add_params_to_uri + + +class OAuth2Error(AuthlibHTTPError): + def __init__(self, description=None, uri=None, + status_code=None, state=None, + redirect_uri=None, redirect_fragment=False, error=None): + super().__init__(error, description, uri, status_code) + self.state = state + self.redirect_uri = redirect_uri + self.redirect_fragment = redirect_fragment + + def get_body(self): + """Get a list of body.""" + error = super().get_body() + if self.state: + error.append(('state', self.state)) + return error + + def __call__(self, uri=None): + if self.redirect_uri: + params = self.get_body() + loc = add_params_to_uri(self.redirect_uri, params, self.redirect_fragment) + return 302, '', [('Location', loc)] + return super().__call__(uri=uri) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/client.py new file mode 100644 index 0000000000000000000000000000000000000000..7adb0c8e242773eacad5fb3539dbd9158e760092 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/client.py @@ -0,0 +1,438 @@ +from authlib.common.security import generate_token +from authlib.common.urls import url_decode +from .rfc6749.parameters import ( + prepare_grant_uri, + prepare_token_request, + parse_authorization_code_response, + parse_implicit_response, +) +from .rfc7009 import prepare_revoke_token_request +from .rfc7636 import create_s256_code_challenge +from .auth import TokenAuth, ClientAuth +from .base import OAuth2Error + +DEFAULT_HEADERS = { + 'Accept': 'application/json', + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' +} + + +class OAuth2Client: + """Construct a new OAuth 2 protocol client. + + :param session: Requests session object to communicate with + authorization server. + :param client_id: Client ID, which you get from client registration. + :param client_secret: Client Secret, which you get from registration. + :param token_endpoint_auth_method: client authentication method for + token endpoint. + :param revocation_endpoint_auth_method: client authentication method for + revocation endpoint. + :param scope: Scope that you needed to access user resources. + :param state: Shared secret to prevent CSRF attack. + :param redirect_uri: Redirect URI you registered as callback. + :param code_challenge_method: PKCE method name, only S256 is supported. + :param token: A dict of token attributes such as ``access_token``, + ``token_type`` and ``expires_at``. + :param token_placement: The place to put token in HTTP request. Available + values: "header", "body", "uri". + :param update_token: A function for you to update token. It accept a + :class:`OAuth2Token` as parameter. + """ + client_auth_class = ClientAuth + token_auth_class = TokenAuth + oauth_error_class = OAuth2Error + + EXTRA_AUTHORIZE_PARAMS = ( + 'response_mode', 'nonce', 'prompt', 'login_hint' + ) + SESSION_REQUEST_PARAMS = [] + + def __init__(self, session, client_id=None, client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, state=None, redirect_uri=None, code_challenge_method=None, + token=None, token_placement='header', update_token=None, **metadata): + + self.session = session + self.client_id = client_id + self.client_secret = client_secret + self.state = state + + if token_endpoint_auth_method is None: + if client_secret: + token_endpoint_auth_method = 'client_secret_basic' + else: + token_endpoint_auth_method = 'none' + + self.token_endpoint_auth_method = token_endpoint_auth_method + + if revocation_endpoint_auth_method is None: + if client_secret: + revocation_endpoint_auth_method = 'client_secret_basic' + else: + revocation_endpoint_auth_method = 'none' + + self.revocation_endpoint_auth_method = revocation_endpoint_auth_method + + self.scope = scope + self.redirect_uri = redirect_uri + self.code_challenge_method = code_challenge_method + + self.token_auth = self.token_auth_class(token, token_placement, self) + self.update_token = update_token + + token_updater = metadata.pop('token_updater', None) + if token_updater: + raise ValueError('update token has been redesigned, checkout the documentation') + + self.metadata = metadata + + self.compliance_hook = { + 'access_token_response': set(), + 'refresh_token_request': set(), + 'refresh_token_response': set(), + 'revoke_token_request': set(), + 'introspect_token_request': set(), + } + self._auth_methods = {} + + def register_client_auth_method(self, auth): + """Extend client authenticate for token endpoint. + + :param auth: an instance to sign the request + """ + if isinstance(auth, tuple): + self._auth_methods[auth[0]] = auth[1] + else: + self._auth_methods[auth.name] = auth + + def client_auth(self, auth_method): + if isinstance(auth_method, str) and auth_method in self._auth_methods: + auth_method = self._auth_methods[auth_method] + return self.client_auth_class( + client_id=self.client_id, + client_secret=self.client_secret, + auth_method=auth_method, + ) + + @property + def token(self): + return self.token_auth.token + + @token.setter + def token(self, token): + self.token_auth.set_token(token) + + def create_authorization_url(self, url, state=None, code_verifier=None, **kwargs): + """Generate an authorization URL and state. + + :param url: Authorization endpoint url, must be HTTPS. + :param state: An optional state string for CSRF protection. If not + given it will be generated for you. + :param code_verifier: An optional code_verifier for code challenge. + :param kwargs: Extra parameters to include. + :return: authorization_url, state + """ + if state is None: + state = generate_token() + + response_type = self.metadata.get('response_type', 'code') + response_type = kwargs.pop('response_type', response_type) + if 'redirect_uri' not in kwargs: + kwargs['redirect_uri'] = self.redirect_uri + if 'scope' not in kwargs: + kwargs['scope'] = self.scope + + if code_verifier and response_type == 'code' and self.code_challenge_method == 'S256': + kwargs['code_challenge'] = create_s256_code_challenge(code_verifier) + kwargs['code_challenge_method'] = self.code_challenge_method + + for k in self.EXTRA_AUTHORIZE_PARAMS: + if k not in kwargs and k in self.metadata: + kwargs[k] = self.metadata[k] + + uri = prepare_grant_uri( + url, client_id=self.client_id, response_type=response_type, + state=state, **kwargs) + return uri, state + + def fetch_token(self, url=None, body='', method='POST', headers=None, + auth=None, grant_type=None, state=None, **kwargs): + """Generic method for fetching an access token from the token endpoint. + + :param url: Access Token endpoint URL, if not configured, + ``authorization_response`` is used to extract token from + its fragment (implicit way). + :param body: Optional application/x-www-form-urlencoded body to add the + include in the token request. Prefer kwargs over body. + :param method: The HTTP method used to make the request. Defaults + to POST, but may also be GET. Other methods should + be added as needed. + :param headers: Dict to default request headers with. + :param auth: An auth tuple or method as accepted by requests. + :param grant_type: Use specified grant_type to fetch token + :return: A :class:`OAuth2Token` object (a dict too). + """ + state = state or self.state + # implicit grant_type + authorization_response = kwargs.pop('authorization_response', None) + if authorization_response and '#' in authorization_response: + return self.token_from_fragment(authorization_response, state) + + session_kwargs = self._extract_session_request_params(kwargs) + + if authorization_response and 'code=' in authorization_response: + grant_type = 'authorization_code' + params = parse_authorization_code_response( + authorization_response, + state=state, + ) + kwargs['code'] = params['code'] + + if grant_type is None: + grant_type = self.metadata.get('grant_type') + + if grant_type is None: + grant_type = _guess_grant_type(kwargs) + self.metadata['grant_type'] = grant_type + + body = self._prepare_token_endpoint_body(body, grant_type, **kwargs) + + if auth is None: + auth = self.client_auth(self.token_endpoint_auth_method) + + if headers is None: + headers = DEFAULT_HEADERS + + if url is None: + url = self.metadata.get('token_endpoint') + + return self._fetch_token( + url, body=body, auth=auth, method=method, + headers=headers, **session_kwargs + ) + + def token_from_fragment(self, authorization_response, state=None): + token = parse_implicit_response(authorization_response, state) + if 'error' in token: + raise self.oauth_error_class( + error=token['error'], + description=token.get('error_description') + ) + self.token = token + return token + + def refresh_token(self, url, refresh_token=None, body='', + auth=None, headers=None, **kwargs): + """Fetch a new access token using a refresh token. + + :param url: Refresh Token endpoint, must be HTTPS. + :param refresh_token: The refresh_token to use. + :param body: Optional application/x-www-form-urlencoded body to add the + include in the token request. Prefer kwargs over body. + :param auth: An auth tuple or method as accepted by requests. + :param headers: Dict to default request headers with. + :return: A :class:`OAuth2Token` object (a dict too). + """ + session_kwargs = self._extract_session_request_params(kwargs) + refresh_token = refresh_token or self.token.get('refresh_token') + if 'scope' not in kwargs and self.scope: + kwargs['scope'] = self.scope + body = prepare_token_request( + 'refresh_token', body, + refresh_token=refresh_token, **kwargs + ) + + if headers is None: + headers = DEFAULT_HEADERS.copy() + + for hook in self.compliance_hook['refresh_token_request']: + url, headers, body = hook(url, headers, body) + + if auth is None: + auth = self.client_auth(self.token_endpoint_auth_method) + + return self._refresh_token( + url, refresh_token=refresh_token, body=body, headers=headers, + auth=auth, **session_kwargs) + + def ensure_active_token(self, token): + if not token.is_expired(): + return True + refresh_token = token.get('refresh_token') + url = self.metadata.get('token_endpoint') + if refresh_token and url: + self.refresh_token(url, refresh_token=refresh_token) + return True + elif self.metadata.get('grant_type') == 'client_credentials': + access_token = token['access_token'] + new_token = self.fetch_token(url, grant_type='client_credentials') + if self.update_token: + self.update_token(new_token, access_token=access_token) + return True + + def revoke_token(self, url, token=None, token_type_hint=None, + body=None, auth=None, headers=None, **kwargs): + """Revoke token method defined via `RFC7009`_. + + :param url: Revoke Token endpoint, must be HTTPS. + :param token: The token to be revoked. + :param token_type_hint: The type of the token that to be revoked. + It can be "access_token" or "refresh_token". + :param body: Optional application/x-www-form-urlencoded body to add the + include in the token request. Prefer kwargs over body. + :param auth: An auth tuple or method as accepted by requests. + :param headers: Dict to default request headers with. + :return: Revocation Response + + .. _`RFC7009`: https://tools.ietf.org/html/rfc7009 + """ + return self._handle_token_hint( + 'revoke_token_request', url, + token=token, token_type_hint=token_type_hint, + body=body, auth=auth, headers=headers, **kwargs) + + def introspect_token(self, url, token=None, token_type_hint=None, + body=None, auth=None, headers=None, **kwargs): + """Implementation of OAuth 2.0 Token Introspection defined via `RFC7662`_. + + :param url: Introspection Endpoint, must be HTTPS. + :param token: The token to be introspected. + :param token_type_hint: The type of the token that to be revoked. + It can be "access_token" or "refresh_token". + :param body: Optional application/x-www-form-urlencoded body to add the + include in the token request. Prefer kwargs over body. + :param auth: An auth tuple or method as accepted by requests. + :param headers: Dict to default request headers with. + :return: Introspection Response + + .. _`RFC7662`: https://tools.ietf.org/html/rfc7662 + """ + return self._handle_token_hint( + 'introspect_token_request', url, + token=token, token_type_hint=token_type_hint, + body=body, auth=auth, headers=headers, **kwargs) + + def register_compliance_hook(self, hook_type, hook): + """Register a hook for request/response tweaking. + + Available hooks are: + + * access_token_response: invoked before token parsing. + * refresh_token_request: invoked before refreshing token. + * refresh_token_response: invoked before refresh token parsing. + * protected_request: invoked before making a request. + * revoke_token_request: invoked before revoking a token. + * introspect_token_request: invoked before introspecting a token. + """ + if hook_type == 'protected_request': + self.token_auth.hooks.add(hook) + return + + if hook_type not in self.compliance_hook: + raise ValueError('Hook type %s is not in %s.', + hook_type, self.compliance_hook) + self.compliance_hook[hook_type].add(hook) + + def parse_response_token(self, resp): + if resp.status_code >= 500: + resp.raise_for_status() + + token = resp.json() + if 'error' in token: + raise self.oauth_error_class( + error=token['error'], + description=token.get('error_description') + ) + self.token = token + return self.token + + def _fetch_token(self, url, body='', headers=None, auth=None, + method='POST', **kwargs): + + if method.upper() == 'POST': + resp = self.session.post( + url, data=dict(url_decode(body)), + headers=headers, auth=auth, **kwargs) + else: + if '?' in url: + url = '&'.join([url, body]) + else: + url = '?'.join([url, body]) + resp = self.session.request(method, url, headers=headers, auth=auth, **kwargs) + + for hook in self.compliance_hook['access_token_response']: + resp = hook(resp) + + return self.parse_response_token(resp) + + def _refresh_token(self, url, refresh_token=None, body='', headers=None, + auth=None, **kwargs): + resp = self._http_post(url, body=body, auth=auth, headers=headers, **kwargs) + + for hook in self.compliance_hook['refresh_token_response']: + resp = hook(resp) + + token = self.parse_response_token(resp) + if 'refresh_token' not in token: + self.token['refresh_token'] = refresh_token + + if callable(self.update_token): + self.update_token(self.token, refresh_token=refresh_token) + + return self.token + + def _handle_token_hint(self, hook, url, token=None, token_type_hint=None, + body=None, auth=None, headers=None, **kwargs): + if token is None and self.token: + token = self.token.get('refresh_token') or self.token.get('access_token') + + if body is None: + body = '' + + body, headers = prepare_revoke_token_request( + token, token_type_hint, body, headers) + + for hook in self.compliance_hook[hook]: + url, headers, body = hook(url, headers, body) + + if auth is None: + auth = self.client_auth(self.revocation_endpoint_auth_method) + + session_kwargs = self._extract_session_request_params(kwargs) + return self._http_post( + url, body, auth=auth, headers=headers, **session_kwargs) + + def _prepare_token_endpoint_body(self, body, grant_type, **kwargs): + if grant_type == 'authorization_code': + if 'redirect_uri' not in kwargs: + kwargs['redirect_uri'] = self.redirect_uri + return prepare_token_request(grant_type, body, **kwargs) + + if 'scope' not in kwargs and self.scope: + kwargs['scope'] = self.scope + return prepare_token_request(grant_type, body, **kwargs) + + def _extract_session_request_params(self, kwargs): + """Extract parameters for session object from the passing ``**kwargs``.""" + rv = {} + for k in self.SESSION_REQUEST_PARAMS: + if k in kwargs: + rv[k] = kwargs.pop(k) + return rv + + def _http_post(self, url, body=None, auth=None, headers=None, **kwargs): + return self.session.post( + url, data=dict(url_decode(body)), + headers=headers, auth=auth, **kwargs) + + +def _guess_grant_type(kwargs): + if 'code' in kwargs: + grant_type = 'authorization_code' + elif 'username' in kwargs and 'password' in kwargs: + grant_type = 'password' + else: + grant_type = 'client_credentials' + return grant_type diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1748e3d44dcd3711f8860d5e6d17bc144af4727 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/__init__.py @@ -0,0 +1,83 @@ +""" + authlib.oauth2.rfc6749 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + The OAuth 2.0 Authorization Framework. + + https://tools.ietf.org/html/rfc6749 +""" + +from .requests import OAuth2Request, JsonRequest +from .wrappers import OAuth2Token +from .errors import ( + OAuth2Error, + AccessDeniedError, + MissingAuthorizationError, + InvalidGrantError, + InvalidClientError, + InvalidRequestError, + InvalidScopeError, + InsecureTransportError, + UnauthorizedClientError, + UnsupportedResponseTypeError, + UnsupportedGrantTypeError, + UnsupportedTokenTypeError, + # exceptions for clients + MissingCodeException, + MissingTokenException, + MissingTokenTypeException, + MismatchingStateException, +) +from .models import ClientMixin, AuthorizationCodeMixin, TokenMixin +from .authenticate_client import ClientAuthentication +from .authorization_server import AuthorizationServer +from .resource_protector import ResourceProtector, TokenValidator +from .token_endpoint import TokenEndpoint +from .grants import ( + BaseGrant, + AuthorizationEndpointMixin, + TokenEndpointMixin, + AuthorizationCodeGrant, + ImplicitGrant, + ResourceOwnerPasswordCredentialsGrant, + ClientCredentialsGrant, + RefreshTokenGrant, +) +from .util import scope_to_list, list_to_scope + +__all__ = [ + 'OAuth2Token', + 'OAuth2Request', 'JsonRequest', + 'OAuth2Error', + 'AccessDeniedError', + 'MissingAuthorizationError', + 'InvalidGrantError', + 'InvalidClientError', + 'InvalidRequestError', + 'InvalidScopeError', + 'InsecureTransportError', + 'UnauthorizedClientError', + 'UnsupportedResponseTypeError', + 'UnsupportedGrantTypeError', + 'UnsupportedTokenTypeError', + 'MissingCodeException', + 'MissingTokenException', + 'MissingTokenTypeException', + 'MismatchingStateException', + 'ClientMixin', 'AuthorizationCodeMixin', 'TokenMixin', + 'ClientAuthentication', + 'AuthorizationServer', + 'ResourceProtector', + 'TokenValidator', + 'TokenEndpoint', + 'BaseGrant', + 'AuthorizationEndpointMixin', + 'TokenEndpointMixin', + 'AuthorizationCodeGrant', + 'ImplicitGrant', + 'ResourceOwnerPasswordCredentialsGrant', + 'ClientCredentialsGrant', + 'RefreshTokenGrant', + 'scope_to_list', 'list_to_scope', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/authenticate_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/authenticate_client.py new file mode 100644 index 0000000000000000000000000000000000000000..adcfd25f5e051c75b78681183ad1baf7a86e1e2a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/authenticate_client.py @@ -0,0 +1,103 @@ +""" + authlib.oauth2.rfc6749.authenticate_client + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Registry of client authentication methods, with 3 built-in methods: + + 1. client_secret_basic + 2. client_secret_post + 3. none + + The "client_secret_basic" method is used a lot in examples of `RFC6749`_, + but the concept of naming are introduced in `RFC7591`_. + + .. _`RFC6749`: https://tools.ietf.org/html/rfc6749 + .. _`RFC7591`: https://tools.ietf.org/html/rfc7591 +""" + +import logging +from .errors import InvalidClientError +from .util import extract_basic_authorization + +log = logging.getLogger(__name__) + +__all__ = ['ClientAuthentication'] + + +class ClientAuthentication: + def __init__(self, query_client): + self.query_client = query_client + self._methods = { + 'none': authenticate_none, + 'client_secret_basic': authenticate_client_secret_basic, + 'client_secret_post': authenticate_client_secret_post, + } + + def register(self, method, func): + self._methods[method] = func + + def authenticate(self, request, methods, endpoint): + for method in methods: + func = self._methods[method] + client = func(self.query_client, request) + if client and client.check_endpoint_auth_method(method, endpoint): + request.auth_method = method + return client + + if 'client_secret_basic' in methods: + raise InvalidClientError(state=request.state, status_code=401) + raise InvalidClientError(state=request.state) + + def __call__(self, request, methods, endpoint='token'): + return self.authenticate(request, methods, endpoint) + + +def authenticate_client_secret_basic(query_client, request): + """Authenticate client by ``client_secret_basic`` method. The client + uses HTTP Basic for authentication. + """ + client_id, client_secret = extract_basic_authorization(request.headers) + if client_id and client_secret: + client = _validate_client(query_client, client_id, request.state, 401) + if client.check_client_secret(client_secret): + log.debug(f'Authenticate {client_id} via "client_secret_basic" success') + return client + log.debug(f'Authenticate {client_id} via "client_secret_basic" failed') + + +def authenticate_client_secret_post(query_client, request): + """Authenticate client by ``client_secret_post`` method. The client + uses POST parameters for authentication. + """ + data = request.form + client_id = data.get('client_id') + client_secret = data.get('client_secret') + if client_id and client_secret: + client = _validate_client(query_client, client_id, request.state) + if client.check_client_secret(client_secret): + log.debug(f'Authenticate {client_id} via "client_secret_post" success') + return client + log.debug(f'Authenticate {client_id} via "client_secret_post" failed') + + +def authenticate_none(query_client, request): + """Authenticate public client by ``none`` method. The client + does not have a client secret. + """ + client_id = request.client_id + if client_id and not request.data.get('client_secret'): + client = _validate_client(query_client, client_id, request.state) + log.debug(f'Authenticate {client_id} via "none" success') + return client + log.debug(f'Authenticate {client_id} via "none" failed') + + +def _validate_client(query_client, client_id, state=None, status_code=400): + if client_id is None: + raise InvalidClientError(state=state, status_code=status_code) + + client = query_client(client_id) + if not client: + raise InvalidClientError(state=state, status_code=status_code) + + return client diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/authorization_server.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/authorization_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3190540e3f63cf089e4048898a2856208db3c0c5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/authorization_server.py @@ -0,0 +1,301 @@ +from authlib.common.errors import ContinueIteration +from .authenticate_client import ClientAuthentication +from .requests import OAuth2Request, JsonRequest +from .errors import ( + OAuth2Error, + InvalidScopeError, + UnsupportedResponseTypeError, + UnsupportedGrantTypeError, +) +from .util import scope_to_list + + +class AuthorizationServer: + """Authorization server that handles Authorization Endpoint and Token + Endpoint. + + :param scopes_supported: A list of supported scopes by this authorization server. + """ + def __init__(self, scopes_supported=None): + self.scopes_supported = scopes_supported + self._token_generators = {} + self._client_auth = None + self._authorization_grants = [] + self._token_grants = [] + self._endpoints = {} + + def query_client(self, client_id): + """Query OAuth client by client_id. The client model class MUST + implement the methods described by + :class:`~authlib.oauth2.rfc6749.ClientMixin`. + """ + raise NotImplementedError() + + def save_token(self, token, request): + """Define function to save the generated token into database.""" + raise NotImplementedError() + + def generate_token(self, grant_type, client, user=None, scope=None, + expires_in=None, include_refresh_token=True): + """Generate the token dict. + + :param grant_type: current requested grant_type. + :param client: the client that making the request. + :param user: current authorized user. + :param expires_in: if provided, use this value as expires_in. + :param scope: current requested scope. + :param include_refresh_token: should refresh_token be included. + :return: Token dict + """ + # generator for a specified grant type + func = self._token_generators.get(grant_type) + if not func: + # default generator for all grant types + func = self._token_generators.get('default') + if not func: + raise RuntimeError('No configured token generator') + + return func( + grant_type=grant_type, client=client, user=user, scope=scope, + expires_in=expires_in, include_refresh_token=include_refresh_token) + + def register_token_generator(self, grant_type, func): + """Register a function as token generator for the given ``grant_type``. + Developers MUST register a default token generator with a special + ``grant_type=default``:: + + def generate_bearer_token(grant_type, client, user=None, scope=None, + expires_in=None, include_refresh_token=True): + token = {'token_type': 'Bearer', 'access_token': ...} + if include_refresh_token: + token['refresh_token'] = ... + ... + return token + + authorization_server.register_token_generator('default', generate_bearer_token) + + If you register a generator for a certain grant type, that generator will only works + for the given grant type:: + + authorization_server.register_token_generator('client_credentials', generate_bearer_token) + + :param grant_type: string name of the grant type + :param func: a function to generate token + """ + self._token_generators[grant_type] = func + + def authenticate_client(self, request, methods, endpoint='token'): + """Authenticate client via HTTP request information with the given + methods, such as ``client_secret_basic``, ``client_secret_post``. + """ + if self._client_auth is None and self.query_client: + self._client_auth = ClientAuthentication(self.query_client) + return self._client_auth(request, methods, endpoint) + + def register_client_auth_method(self, method, func): + """Add more client auth method. The default methods are: + + * none: The client is a public client and does not have a client secret + * client_secret_post: The client uses the HTTP POST parameters + * client_secret_basic: The client uses HTTP Basic + + :param method: Name of the Auth method + :param func: Function to authenticate the client + + The auth method accept two parameters: ``query_client`` and ``request``, + an example for this method:: + + def authenticate_client_via_custom(query_client, request): + client_id = request.headers['X-Client-Id'] + client = query_client(client_id) + do_some_validation(client) + return client + + authorization_server.register_client_auth_method( + 'custom', authenticate_client_via_custom) + """ + if self._client_auth is None and self.query_client: + self._client_auth = ClientAuthentication(self.query_client) + + self._client_auth.register(method, func) + + def get_error_uri(self, request, error): + """Return a URI for the given error, framework may implement this method.""" + return None + + def send_signal(self, name, *args, **kwargs): + """Framework integration can re-implement this method to support + signal system. + """ + raise NotImplementedError() + + def create_oauth2_request(self, request) -> OAuth2Request: + """This method MUST be implemented in framework integrations. It is + used to create an OAuth2Request instance. + + :param request: the "request" instance in framework + :return: OAuth2Request instance + """ + raise NotImplementedError() + + def create_json_request(self, request) -> JsonRequest: + """This method MUST be implemented in framework integrations. It is + used to create an HttpRequest instance. + + :param request: the "request" instance in framework + :return: HttpRequest instance + """ + raise NotImplementedError() + + def handle_response(self, status, body, headers): + """Return HTTP response. Framework MUST implement this function.""" + raise NotImplementedError() + + def validate_requested_scope(self, scope, state=None): + """Validate if requested scope is supported by Authorization Server. + Developers CAN re-write this method to meet your needs. + """ + if scope and self.scopes_supported: + scopes = set(scope_to_list(scope)) + if not set(self.scopes_supported).issuperset(scopes): + raise InvalidScopeError(state=state) + + def register_grant(self, grant_cls, extensions=None): + """Register a grant class into the endpoint registry. Developers + can implement the grants in ``authlib.oauth2.rfc6749.grants`` and + register with this method:: + + class AuthorizationCodeGrant(grants.AuthorizationCodeGrant): + def authenticate_user(self, credential): + # ... + + authorization_server.register_grant(AuthorizationCodeGrant) + + :param grant_cls: a grant class. + :param extensions: extensions for the grant class. + """ + if hasattr(grant_cls, 'check_authorization_endpoint'): + self._authorization_grants.append((grant_cls, extensions)) + if hasattr(grant_cls, 'check_token_endpoint'): + self._token_grants.append((grant_cls, extensions)) + + def register_endpoint(self, endpoint): + """Add extra endpoint to authorization server. e.g. + RevocationEndpoint:: + + authorization_server.register_endpoint(RevocationEndpoint) + + :param endpoint_cls: A endpoint class or instance. + """ + if isinstance(endpoint, type): + endpoint = endpoint(self) + else: + endpoint.server = self + + endpoints = self._endpoints.setdefault(endpoint.ENDPOINT_NAME, []) + endpoints.append(endpoint) + + def get_authorization_grant(self, request): + """Find the authorization grant for current request. + + :param request: OAuth2Request instance. + :return: grant instance + """ + for (grant_cls, extensions) in self._authorization_grants: + if grant_cls.check_authorization_endpoint(request): + return _create_grant(grant_cls, extensions, request, self) + raise UnsupportedResponseTypeError(request.response_type) + + def get_consent_grant(self, request=None, end_user=None): + """Validate current HTTP request for authorization page. This page + is designed for resource owner to grant or deny the authorization. + """ + request = self.create_oauth2_request(request) + request.user = end_user + + grant = self.get_authorization_grant(request) + grant.validate_consent_request() + return grant + + def get_token_grant(self, request): + """Find the token grant for current request. + + :param request: OAuth2Request instance. + :return: grant instance + """ + for (grant_cls, extensions) in self._token_grants: + if grant_cls.check_token_endpoint(request): + return _create_grant(grant_cls, extensions, request, self) + raise UnsupportedGrantTypeError(request.grant_type) + + def create_endpoint_response(self, name, request=None): + """Validate endpoint request and create endpoint response. + + :param name: Endpoint name + :param request: HTTP request instance. + :return: Response + """ + if name not in self._endpoints: + raise RuntimeError(f'There is no "{name}" endpoint.') + + endpoints = self._endpoints[name] + for endpoint in endpoints: + request = endpoint.create_endpoint_request(request) + try: + return self.handle_response(*endpoint(request)) + except ContinueIteration: + continue + except OAuth2Error as error: + return self.handle_error_response(request, error) + + def create_authorization_response(self, request=None, grant_user=None): + """Validate authorization request and create authorization response. + + :param request: HTTP request instance. + :param grant_user: if granted, it is resource owner. If denied, + it is None. + :returns: Response + """ + if not isinstance(request, OAuth2Request): + request = self.create_oauth2_request(request) + + try: + grant = self.get_authorization_grant(request) + except UnsupportedResponseTypeError as error: + return self.handle_error_response(request, error) + + try: + redirect_uri = grant.validate_authorization_request() + args = grant.create_authorization_response(redirect_uri, grant_user) + return self.handle_response(*args) + except OAuth2Error as error: + return self.handle_error_response(request, error) + + def create_token_response(self, request=None): + """Validate token request and create token response. + + :param request: HTTP request instance + """ + request = self.create_oauth2_request(request) + try: + grant = self.get_token_grant(request) + except UnsupportedGrantTypeError as error: + return self.handle_error_response(request, error) + + try: + grant.validate_token_request() + args = grant.create_token_response() + return self.handle_response(*args) + except OAuth2Error as error: + return self.handle_error_response(request, error) + + def handle_error_response(self, request, error): + return self.handle_response(*error(self.get_error_uri(request, error))) + + +def _create_grant(grant_cls, extensions, request, server): + grant = grant_cls(request, server) + if extensions: + for ext in extensions: + ext(grant) + return grant diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/errors.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..63ffb47e1ab75fc419beefa83889d50e307ef35f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/errors.py @@ -0,0 +1,233 @@ +""" + authlib.oauth2.rfc6749.errors + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Implementation for OAuth 2 Error Response. A basic error has + parameters: + + error + REQUIRED. A single ASCII [USASCII] error code. + + error_description + OPTIONAL. Human-readable ASCII [USASCII] text providing + additional information, used to assist the client developer in + understanding the error that occurred. + + error_uri + OPTIONAL. A URI identifying a human-readable web page with + information about the error, used to provide the client + developer with additional information about the error. + Values for the "error_uri" parameter MUST conform to the + URI-reference syntax and thus MUST NOT include characters + outside the set %x21 / %x23-5B / %x5D-7E. + + state + REQUIRED if a "state" parameter was present in the client + authorization request. The exact value received from the + client. + + https://tools.ietf.org/html/rfc6749#section-5.2 + + :copyright: (c) 2017 by Hsiaoming Yang. +""" +from authlib.oauth2.base import OAuth2Error +from authlib.common.security import is_secure_transport + +__all__ = [ + 'OAuth2Error', + 'InsecureTransportError', 'InvalidRequestError', + 'InvalidClientError', 'UnauthorizedClientError', 'InvalidGrantError', + 'UnsupportedResponseTypeError', 'UnsupportedGrantTypeError', + 'InvalidScopeError', 'AccessDeniedError', + 'MissingAuthorizationError', 'UnsupportedTokenTypeError', + 'MissingCodeException', 'MissingTokenException', + 'MissingTokenTypeException', 'MismatchingStateException', +] + + +class InsecureTransportError(OAuth2Error): + error = 'insecure_transport' + description = 'OAuth 2 MUST utilize https.' + + @classmethod + def check(cls, uri): + """Check and raise InsecureTransportError with the given URI.""" + if not is_secure_transport(uri): + raise cls() + + +class InvalidRequestError(OAuth2Error): + """The request is missing a required parameter, includes an + unsupported parameter value (other than grant type), + repeats a parameter, includes multiple credentials, + utilizes more than one mechanism for authenticating the + client, or is otherwise malformed. + + https://tools.ietf.org/html/rfc6749#section-5.2 + """ + error = 'invalid_request' + + +class InvalidClientError(OAuth2Error): + """Client authentication failed (e.g., unknown client, no + client authentication included, or unsupported + authentication method). The authorization server MAY + return an HTTP 401 (Unauthorized) status code to indicate + which HTTP authentication schemes are supported. If the + client attempted to authenticate via the "Authorization" + request header field, the authorization server MUST + respond with an HTTP 401 (Unauthorized) status code and + include the "WWW-Authenticate" response header field + matching the authentication scheme used by the client. + + https://tools.ietf.org/html/rfc6749#section-5.2 + """ + error = 'invalid_client' + status_code = 400 + + def get_headers(self): + headers = super().get_headers() + if self.status_code == 401: + error_description = self.get_error_description() + # safe escape + error_description = error_description.replace('"', '|') + extras = [ + f'error="{self.error}"', + f'error_description="{error_description}"' + ] + headers.append( + ('WWW-Authenticate', 'Basic ' + ', '.join(extras)) + ) + return headers + + +class InvalidGrantError(OAuth2Error): + """The provided authorization grant (e.g., authorization + code, resource owner credentials) or refresh token is + invalid, expired, revoked, does not match the redirection + URI used in the authorization request, or was issued to + another client. + + https://tools.ietf.org/html/rfc6749#section-5.2 + """ + error = 'invalid_grant' + + +class UnauthorizedClientError(OAuth2Error): + """ The authenticated client is not authorized to use this + authorization grant type. + + https://tools.ietf.org/html/rfc6749#section-5.2 + """ + error = 'unauthorized_client' + + +class UnsupportedResponseTypeError(OAuth2Error): + """The authorization server does not support obtaining + an access token using this method.""" + error = 'unsupported_response_type' + + def __init__(self, response_type): + super().__init__() + self.response_type = response_type + + def get_error_description(self): + return f'response_type={self.response_type} is not supported' + + +class UnsupportedGrantTypeError(OAuth2Error): + """The authorization grant type is not supported by the + authorization server. + + https://tools.ietf.org/html/rfc6749#section-5.2 + """ + error = 'unsupported_grant_type' + + def __init__(self, grant_type): + super().__init__() + self.grant_type = grant_type + + def get_error_description(self): + return f'grant_type={self.grant_type} is not supported' + + +class InvalidScopeError(OAuth2Error): + """The requested scope is invalid, unknown, malformed, or + exceeds the scope granted by the resource owner. + + https://tools.ietf.org/html/rfc6749#section-5.2 + """ + error = 'invalid_scope' + description = 'The requested scope is invalid, unknown, or malformed.' + + +class AccessDeniedError(OAuth2Error): + """The resource owner or authorization server denied the request. + + Used in authorization endpoint for "code" and "implicit". Defined in + `Section 4.1.2.1`_. + + .. _`Section 4.1.2.1`: https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + """ + error = 'access_denied' + description = 'The resource owner or authorization server denied the request' + + +# -- below are extended errors -- # + + +class ForbiddenError(OAuth2Error): + status_code = 401 + + def __init__(self, auth_type=None, realm=None): + super().__init__() + self.auth_type = auth_type + self.realm = realm + + def get_headers(self): + headers = super().get_headers() + if not self.auth_type: + return headers + + extras = [] + if self.realm: + extras.append(f'realm="{self.realm}"') + extras.append(f'error="{self.error}"') + error_description = self.description + extras.append(f'error_description="{error_description}"') + headers.append( + ('WWW-Authenticate', f'{self.auth_type} ' + ', '.join(extras)) + ) + return headers + + +class MissingAuthorizationError(ForbiddenError): + error = 'missing_authorization' + description = 'Missing "Authorization" in headers.' + + +class UnsupportedTokenTypeError(ForbiddenError): + error = 'unsupported_token_type' + + +# -- exceptions for clients -- # + + +class MissingCodeException(OAuth2Error): + error = 'missing_code' + description = 'Missing "code" in response.' + + +class MissingTokenException(OAuth2Error): + error = 'missing_token' + description = 'Missing "access_token" in response.' + + +class MissingTokenTypeException(OAuth2Error): + error = 'missing_token_type' + description = 'Missing "token_type" in response.' + + +class MismatchingStateException(OAuth2Error): + error = 'mismatching_state' + description = 'CSRF Warning! State not equal in request and response.' diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b1797565fd7bf8e00efb9180176efdc0e8033209 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/__init__.py @@ -0,0 +1,37 @@ +""" + authlib.oauth2.rfc6749.grants + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Implementation for `Section 4`_ of "Obtaining Authorization". + + To request an access token, the client obtains authorization from the + resource owner. The authorization is expressed in the form of an + authorization grant, which the client uses to request the access + token. OAuth defines four grant types: + + 1. authorization code + 2. implicit + 3. resource owner password credentials + 4. client credentials. + + It also provides an extension mechanism for defining additional grant + types. Authlib defines refresh_token as a grant type too. + + .. _`Section 4`: https://tools.ietf.org/html/rfc6749#section-4 +""" + +# flake8: noqa + +from .base import BaseGrant, AuthorizationEndpointMixin, TokenEndpointMixin +from .authorization_code import AuthorizationCodeGrant +from .implicit import ImplicitGrant +from .resource_owner_password_credentials import ResourceOwnerPasswordCredentialsGrant +from .client_credentials import ClientCredentialsGrant +from .refresh_token import RefreshTokenGrant + +__all__ = [ + 'BaseGrant', 'AuthorizationEndpointMixin', 'TokenEndpointMixin', + 'AuthorizationCodeGrant', 'ImplicitGrant', + 'ResourceOwnerPasswordCredentialsGrant', + 'ClientCredentialsGrant', 'RefreshTokenGrant', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/authorization_code.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/authorization_code.py new file mode 100644 index 0000000000000000000000000000000000000000..76a51de1d33c540f7460293ae768189289c1a7f8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/authorization_code.py @@ -0,0 +1,378 @@ +import logging +from authlib.common.urls import add_params_to_uri +from authlib.common.security import generate_token +from .base import BaseGrant, AuthorizationEndpointMixin, TokenEndpointMixin +from ..errors import ( + OAuth2Error, + UnauthorizedClientError, + InvalidClientError, + InvalidGrantError, + InvalidRequestError, + AccessDeniedError, +) + +log = logging.getLogger(__name__) + + +class AuthorizationCodeGrant(BaseGrant, AuthorizationEndpointMixin, TokenEndpointMixin): + """The authorization code grant type is used to obtain both access + tokens and refresh tokens and is optimized for confidential clients. + Since this is a redirection-based flow, the client must be capable of + interacting with the resource owner's user-agent (typically a web + browser) and capable of receiving incoming requests (via redirection) + from the authorization server:: + + +----------+ + | Resource | + | Owner | + | | + +----------+ + ^ + | + (B) + +----|-----+ Client Identifier +---------------+ + | -+----(A)-- & Redirection URI ---->| | + | User- | | Authorization | + | Agent -+----(B)-- User authenticates --->| Server | + | | | | + | -+----(C)-- Authorization Code ---<| | + +-|----|---+ +---------------+ + | | ^ v + (A) (C) | | + | | | | + ^ v | | + +---------+ | | + | |>---(D)-- Authorization Code ---------' | + | Client | & Redirection URI | + | | | + | |<---(E)----- Access Token -------------------' + +---------+ (w/ Optional Refresh Token) + """ + #: Allowed client auth methods for token endpoint + TOKEN_ENDPOINT_AUTH_METHODS = ['client_secret_basic', 'client_secret_post'] + + #: Generated "code" length + AUTHORIZATION_CODE_LENGTH = 48 + + RESPONSE_TYPES = {'code'} + GRANT_TYPE = 'authorization_code' + + def validate_authorization_request(self): + """The client constructs the request URI by adding the following + parameters to the query component of the authorization endpoint URI + using the "application/x-www-form-urlencoded" format. + Per `Section 4.1.1`_. + + response_type + REQUIRED. Value MUST be set to "code". + + client_id + REQUIRED. The client identifier as described in Section 2.2. + + redirect_uri + OPTIONAL. As described in Section 3.1.2. + + scope + OPTIONAL. The scope of the access request as described by + Section 3.3. + + state + RECOMMENDED. An opaque value used by the client to maintain + state between the request and callback. The authorization + server includes this value when redirecting the user-agent back + to the client. The parameter SHOULD be used for preventing + cross-site request forgery as described in Section 10.12. + + The client directs the resource owner to the constructed URI using an + HTTP redirection response, or by other means available to it via the + user-agent. + + For example, the client directs the user-agent to make the following + HTTP request using TLS (with extra line breaks for display purposes + only): + + .. code-block:: http + + GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz + &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1 + Host: server.example.com + + The authorization server validates the request to ensure that all + required parameters are present and valid. If the request is valid, + the authorization server authenticates the resource owner and obtains + an authorization decision (by asking the resource owner or by + establishing approval via other means). + + .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1 + """ + return validate_code_authorization_request(self) + + def create_authorization_response(self, redirect_uri: str, grant_user): + """If the resource owner grants the access request, the authorization + server issues an authorization code and delivers it to the client by + adding the following parameters to the query component of the + redirection URI using the "application/x-www-form-urlencoded" format. + Per `Section 4.1.2`_. + + code + REQUIRED. The authorization code generated by the + authorization server. The authorization code MUST expire + shortly after it is issued to mitigate the risk of leaks. A + maximum authorization code lifetime of 10 minutes is + RECOMMENDED. The client MUST NOT use the authorization code + more than once. If an authorization code is used more than + once, the authorization server MUST deny the request and SHOULD + revoke (when possible) all tokens previously issued based on + that authorization code. The authorization code is bound to + the client identifier and redirection URI. + state + REQUIRED if the "state" parameter was present in the client + authorization request. The exact value received from the + client. + + For example, the authorization server redirects the user-agent by + sending the following HTTP response. + + .. code-block:: http + + HTTP/1.1 302 Found + Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA + &state=xyz + + .. _`Section 4.1.2`: https://tools.ietf.org/html/rfc6749#section-4.1.2 + + :param redirect_uri: Redirect to the given URI for the authorization + :param grant_user: if resource owner granted the request, pass this + resource owner, otherwise pass None. + :returns: (status_code, body, headers) + """ + if not grant_user: + raise AccessDeniedError(state=self.request.state, redirect_uri=redirect_uri) + + self.request.user = grant_user + + code = self.generate_authorization_code() + self.save_authorization_code(code, self.request) + + params = [('code', code)] + if self.request.state: + params.append(('state', self.request.state)) + uri = add_params_to_uri(redirect_uri, params) + headers = [('Location', uri)] + return 302, '', headers + + def validate_token_request(self): + """The client makes a request to the token endpoint by sending the + following parameters using the "application/x-www-form-urlencoded" + format per `Section 4.1.3`_: + + grant_type + REQUIRED. Value MUST be set to "authorization_code". + + code + REQUIRED. The authorization code received from the + authorization server. + + redirect_uri + REQUIRED, if the "redirect_uri" parameter was included in the + authorization request as described in Section 4.1.1, and their + values MUST be identical. + + client_id + REQUIRED, if the client is not authenticating with the + authorization server as described in Section 3.2.1. + + If the client type is confidential or the client was issued client + credentials (or assigned other authentication requirements), the + client MUST authenticate with the authorization server as described + in Section 3.2.1. + + For example, the client makes the following HTTP request using TLS: + + .. code-block:: http + + POST /token HTTP/1.1 + Host: server.example.com + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + Content-Type: application/x-www-form-urlencoded + + grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA + &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb + + .. _`Section 4.1.3`: https://tools.ietf.org/html/rfc6749#section-4.1.3 + """ + # ignore validate for grant_type, since it is validated by + # check_token_endpoint + + # authenticate the client if client authentication is included + client = self.authenticate_token_endpoint_client() + + log.debug('Validate token request of %r', client) + if not client.check_grant_type(self.GRANT_TYPE): + raise UnauthorizedClientError( + f'The client is not authorized to use "grant_type={self.GRANT_TYPE}"') + + code = self.request.form.get('code') + if code is None: + raise InvalidRequestError('Missing "code" in request.') + + # ensure that the authorization code was issued to the authenticated + # confidential client, or if the client is public, ensure that the + # code was issued to "client_id" in the request + authorization_code = self.query_authorization_code(code, client) + if not authorization_code: + raise InvalidGrantError('Invalid "code" in request.') + + # validate redirect_uri parameter + log.debug('Validate token redirect_uri of %r', client) + redirect_uri = self.request.redirect_uri + original_redirect_uri = authorization_code.get_redirect_uri() + if original_redirect_uri and redirect_uri != original_redirect_uri: + raise InvalidGrantError('Invalid "redirect_uri" in request.') + + # save for create_token_response + self.request.client = client + self.request.authorization_code = authorization_code + self.execute_hook('after_validate_token_request') + + def create_token_response(self): + """If the access token request is valid and authorized, the + authorization server issues an access token and optional refresh + token as described in Section 5.1. If the request client + authentication failed or is invalid, the authorization server returns + an error response as described in Section 5.2. Per `Section 4.1.4`_. + + An example successful response: + + .. code-block:: http + + HTTP/1.1 200 OK + Content-Type: application/json + Cache-Control: no-store + Pragma: no-cache + + { + "access_token":"2YotnFZFEjr1zCsicMWpAA", + "token_type":"example", + "expires_in":3600, + "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", + "example_parameter":"example_value" + } + + :returns: (status_code, body, headers) + + .. _`Section 4.1.4`: https://tools.ietf.org/html/rfc6749#section-4.1.4 + """ + client = self.request.client + authorization_code = self.request.authorization_code + + user = self.authenticate_user(authorization_code) + if not user: + raise InvalidGrantError('There is no "user" for this code.') + self.request.user = user + + scope = authorization_code.get_scope() + token = self.generate_token( + user=user, + scope=scope, + include_refresh_token=client.check_grant_type('refresh_token'), + ) + log.debug('Issue token %r to %r', token, client) + + self.save_token(token) + self.execute_hook('process_token', token=token) + self.delete_authorization_code(authorization_code) + return 200, token, self.TOKEN_RESPONSE_HEADER + + def generate_authorization_code(self): + """"The method to generate "code" value for authorization code data. + Developers may rewrite this method, or customize the code length with:: + + class MyAuthorizationCodeGrant(AuthorizationCodeGrant): + AUTHORIZATION_CODE_LENGTH = 32 # default is 48 + """ + return generate_token(self.AUTHORIZATION_CODE_LENGTH) + + def save_authorization_code(self, code, request): + """Save authorization_code for later use. Developers MUST implement + it in subclass. Here is an example:: + + def save_authorization_code(self, code, request): + client = request.client + item = AuthorizationCode( + code=code, + client_id=client.client_id, + redirect_uri=request.redirect_uri, + scope=request.scope, + user_id=request.user.id, + ) + item.save() + """ + raise NotImplementedError() + + def query_authorization_code(self, code, client): # pragma: no cover + """Get authorization_code from previously savings. Developers MUST + implement it in subclass:: + + def query_authorization_code(self, code, client): + return Authorization.get(code=code, client_id=client.client_id) + + :param code: a string represent the code. + :param client: client related to this code. + :return: authorization_code object + """ + raise NotImplementedError() + + def delete_authorization_code(self, authorization_code): + """Delete authorization code from database or cache. Developers MUST + implement it in subclass, e.g.:: + + def delete_authorization_code(self, authorization_code): + authorization_code.delete() + + :param authorization_code: the instance of authorization_code + """ + raise NotImplementedError() + + def authenticate_user(self, authorization_code): + """Authenticate the user related to this authorization_code. Developers + MUST implement this method in subclass, e.g.:: + + def authenticate_user(self, authorization_code): + return User.get(authorization_code.user_id) + + :param authorization_code: AuthorizationCode object + :return: user + """ + raise NotImplementedError() + + +def validate_code_authorization_request(grant): + request = grant.request + client_id = request.client_id + log.debug('Validate authorization request of %r', client_id) + + if client_id is None: + raise InvalidClientError(state=request.state) + + client = grant.server.query_client(client_id) + if not client: + raise InvalidClientError(state=request.state) + + redirect_uri = grant.validate_authorization_redirect_uri(request, client) + response_type = request.response_type + if not client.check_response_type(response_type): + raise UnauthorizedClientError( + f'The client is not authorized to use "response_type={response_type}"', + state=grant.request.state, + redirect_uri=redirect_uri, + ) + + try: + grant.request.client = client + grant.validate_requested_scope() + grant.execute_hook('after_validate_authorization_request') + except OAuth2Error as error: + error.redirect_uri = redirect_uri + raise error + return redirect_uri diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/base.py new file mode 100644 index 0000000000000000000000000000000000000000..0d2bf453efc2ebdc83fde04f9b68c3e191b01a49 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/base.py @@ -0,0 +1,148 @@ +from authlib.consts import default_json_headers +from ..requests import OAuth2Request +from ..errors import InvalidRequestError + + +class BaseGrant: + #: Allowed client auth methods for token endpoint + TOKEN_ENDPOINT_AUTH_METHODS = ['client_secret_basic'] + + #: Designed for which "grant_type" + GRANT_TYPE = None + + # NOTE: there is no charset for application/json, since + # application/json should always in UTF-8. + # The example on RFC is incorrect. + # https://tools.ietf.org/html/rfc4627 + TOKEN_RESPONSE_HEADER = default_json_headers + + def __init__(self, request: OAuth2Request, server): + self.prompt = None + self.redirect_uri = None + self.request = request + self.server = server + self._hooks = { + 'after_validate_authorization_request': set(), + 'after_validate_consent_request': set(), + 'after_validate_token_request': set(), + 'process_token': set(), + } + + @property + def client(self): + return self.request.client + + def generate_token(self, user=None, scope=None, grant_type=None, + expires_in=None, include_refresh_token=True): + if grant_type is None: + grant_type = self.GRANT_TYPE + return self.server.generate_token( + client=self.request.client, + grant_type=grant_type, + user=user, + scope=scope, + expires_in=expires_in, + include_refresh_token=include_refresh_token, + ) + + def authenticate_token_endpoint_client(self): + """Authenticate client with the given methods for token endpoint. + + For example, the client makes the following HTTP request using TLS: + + .. code-block:: http + + POST /token HTTP/1.1 + Host: server.example.com + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + Content-Type: application/x-www-form-urlencoded + + grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA + &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb + + Default available methods are: "none", "client_secret_basic" and + "client_secret_post". + + :return: client + """ + client = self.server.authenticate_client( + self.request, self.TOKEN_ENDPOINT_AUTH_METHODS) + self.server.send_signal( + 'after_authenticate_client', + client=client, grant=self) + return client + + def save_token(self, token): + """A method to save token into database.""" + return self.server.save_token(token, self.request) + + def validate_requested_scope(self): + """Validate if requested scope is supported by Authorization Server.""" + scope = self.request.scope + state = self.request.state + return self.server.validate_requested_scope(scope, state) + + def register_hook(self, hook_type, hook): + if hook_type not in self._hooks: + raise ValueError('Hook type %s is not in %s.', + hook_type, self._hooks) + self._hooks[hook_type].add(hook) + + def execute_hook(self, hook_type, *args, **kwargs): + for hook in self._hooks[hook_type]: + hook(self, *args, **kwargs) + + +class TokenEndpointMixin: + #: Allowed HTTP methods of this token endpoint + TOKEN_ENDPOINT_HTTP_METHODS = ['POST'] + + #: Designed for which "grant_type" + GRANT_TYPE = None + + @classmethod + def check_token_endpoint(cls, request: OAuth2Request): + return request.grant_type == cls.GRANT_TYPE and \ + request.method in cls.TOKEN_ENDPOINT_HTTP_METHODS + + def validate_token_request(self): + raise NotImplementedError() + + def create_token_response(self): + raise NotImplementedError() + + +class AuthorizationEndpointMixin: + RESPONSE_TYPES = set() + ERROR_RESPONSE_FRAGMENT = False + + @classmethod + def check_authorization_endpoint(cls, request: OAuth2Request): + return request.response_type in cls.RESPONSE_TYPES + + @staticmethod + def validate_authorization_redirect_uri(request: OAuth2Request, client): + if request.redirect_uri: + if not client.check_redirect_uri(request.redirect_uri): + raise InvalidRequestError( + f'Redirect URI {request.redirect_uri} is not supported by client.', + state=request.state) + return request.redirect_uri + else: + redirect_uri = client.get_default_redirect_uri() + if not redirect_uri: + raise InvalidRequestError( + 'Missing "redirect_uri" in request.', + state=request.state) + return redirect_uri + + def validate_consent_request(self): + redirect_uri = self.validate_authorization_request() + self.execute_hook('after_validate_consent_request', redirect_uri) + self.redirect_uri = redirect_uri + + def validate_authorization_request(self): + raise NotImplementedError() + + def create_authorization_response(self, redirect_uri: str, grant_user): + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/client_credentials.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/client_credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..57249cba7d80d281ea3166a135a2b62166593e93 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/client_credentials.py @@ -0,0 +1,102 @@ +import logging +from .base import BaseGrant, TokenEndpointMixin +from ..errors import UnauthorizedClientError + +log = logging.getLogger(__name__) + + +class ClientCredentialsGrant(BaseGrant, TokenEndpointMixin): + """The client can request an access token using only its client + credentials (or other supported means of authentication) when the + client is requesting access to the protected resources under its + control, or those of another resource owner that have been previously + arranged with the authorization server. + + The client credentials grant type MUST only be used by confidential + clients:: + + +---------+ +---------------+ + | | | | + | |>--(A)- Client Authentication --->| Authorization | + | Client | | Server | + | |<--(B)---- Access Token ---------<| | + | | | | + +---------+ +---------------+ + + https://tools.ietf.org/html/rfc6749#section-4.4 + """ + GRANT_TYPE = 'client_credentials' + + def validate_token_request(self): + """The client makes a request to the token endpoint by adding the + following parameters using the "application/x-www-form-urlencoded" + format per Appendix B with a character encoding of UTF-8 in the HTTP + request entity-body: + + grant_type + REQUIRED. Value MUST be set to "client_credentials". + + scope + OPTIONAL. The scope of the access request as described by + Section 3.3. + + The client MUST authenticate with the authorization server as + described in Section 3.2.1. + + For example, the client makes the following HTTP request using + transport-layer security (with extra line breaks for display purposes + only): + + .. code-block:: http + + POST /token HTTP/1.1 + Host: server.example.com + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + Content-Type: application/x-www-form-urlencoded + + grant_type=client_credentials + + The authorization server MUST authenticate the client. + """ + + # ignore validate for grant_type, since it is validated by + # check_token_endpoint + client = self.authenticate_token_endpoint_client() + log.debug('Validate token request of %r', client) + + if not client.check_grant_type(self.GRANT_TYPE): + raise UnauthorizedClientError() + + self.request.client = client + self.validate_requested_scope() + + def create_token_response(self): + """If the access token request is valid and authorized, the + authorization server issues an access token as described in + Section 5.1. A refresh token SHOULD NOT be included. If the request + failed client authentication or is invalid, the authorization server + returns an error response as described in Section 5.2. + + An example successful response: + + .. code-block:: http + + HTTP/1.1 200 OK + Content-Type: application/json + Cache-Control: no-store + Pragma: no-cache + + { + "access_token":"2YotnFZFEjr1zCsicMWpAA", + "token_type":"example", + "expires_in":3600, + "example_parameter":"example_value" + } + + :returns: (status_code, body, headers) + """ + token = self.generate_token(scope=self.request.scope, include_refresh_token=False) + log.debug('Issue token %r to %r', token, self.client) + self.save_token(token) + self.execute_hook('process_token', self, token=token) + return 200, token, self.TOKEN_RESPONSE_HEADER diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/implicit.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/implicit.py new file mode 100644 index 0000000000000000000000000000000000000000..75b12be436ccd8b8cf0149058a10bbb0f4b21a33 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/implicit.py @@ -0,0 +1,229 @@ +import logging +from authlib.common.urls import add_params_to_uri +from .base import BaseGrant, AuthorizationEndpointMixin +from ..errors import ( + OAuth2Error, + UnauthorizedClientError, + AccessDeniedError, +) + +log = logging.getLogger(__name__) + + +class ImplicitGrant(BaseGrant, AuthorizationEndpointMixin): + """The implicit grant type is used to obtain access tokens (it does not + support the issuance of refresh tokens) and is optimized for public + clients known to operate a particular redirection URI. These clients + are typically implemented in a browser using a scripting language + such as JavaScript. + + Since this is a redirection-based flow, the client must be capable of + interacting with the resource owner's user-agent (typically a web + browser) and capable of receiving incoming requests (via redirection) + from the authorization server. + + Unlike the authorization code grant type, in which the client makes + separate requests for authorization and for an access token, the + client receives the access token as the result of the authorization + request. + + The implicit grant type does not include client authentication, and + relies on the presence of the resource owner and the registration of + the redirection URI. Because the access token is encoded into the + redirection URI, it may be exposed to the resource owner and other + applications residing on the same device:: + + +----------+ + | Resource | + | Owner | + | | + +----------+ + ^ + | + (B) + +----|-----+ Client Identifier +---------------+ + | -+----(A)-- & Redirection URI --->| | + | User- | | Authorization | + | Agent -|----(B)-- User authenticates -->| Server | + | | | | + | |<---(C)--- Redirection URI ----<| | + | | with Access Token +---------------+ + | | in Fragment + | | +---------------+ + | |----(D)--- Redirection URI ---->| Web-Hosted | + | | without Fragment | Client | + | | | Resource | + | (F) |<---(E)------- Script ---------<| | + | | +---------------+ + +-|--------+ + | | + (A) (G) Access Token + | | + ^ v + +---------+ + | | + | Client | + | | + +---------+ + """ + #: authorization_code grant type has authorization endpoint + AUTHORIZATION_ENDPOINT = True + #: Allowed client auth methods for token endpoint + TOKEN_ENDPOINT_AUTH_METHODS = ['none'] + + RESPONSE_TYPES = {'token'} + GRANT_TYPE = 'implicit' + ERROR_RESPONSE_FRAGMENT = True + + def validate_authorization_request(self): + """The client constructs the request URI by adding the following + parameters to the query component of the authorization endpoint URI + using the "application/x-www-form-urlencoded" format. + Per `Section 4.2.1`_. + + response_type + REQUIRED. Value MUST be set to "token". + + client_id + REQUIRED. The client identifier as described in Section 2.2. + + redirect_uri + OPTIONAL. As described in Section 3.1.2. + + scope + OPTIONAL. The scope of the access request as described by + Section 3.3. + + state + RECOMMENDED. An opaque value used by the client to maintain + state between the request and callback. The authorization + server includes this value when redirecting the user-agent back + to the client. The parameter SHOULD be used for preventing + cross-site request forgery as described in Section 10.12. + + The client directs the resource owner to the constructed URI using an + HTTP redirection response, or by other means available to it via the + user-agent. + + For example, the client directs the user-agent to make the following + HTTP request using TLS: + + .. code-block:: http + + GET /authorize?response_type=token&client_id=s6BhdRkqt3&state=xyz + &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1 + Host: server.example.com + + .. _`Section 4.2.1`: https://tools.ietf.org/html/rfc6749#section-4.2.1 + """ + # ignore validate for response_type, since it is validated by + # check_authorization_endpoint + + # The implicit grant type is optimized for public clients + client = self.authenticate_token_endpoint_client() + log.debug('Validate authorization request of %r', client) + + redirect_uri = self.validate_authorization_redirect_uri( + self.request, client) + + response_type = self.request.response_type + if not client.check_response_type(response_type): + raise UnauthorizedClientError( + 'The client is not authorized to use ' + '"response_type={}"'.format(response_type), + state=self.request.state, + redirect_uri=redirect_uri, + redirect_fragment=True, + ) + + try: + self.request.client = client + self.validate_requested_scope() + self.execute_hook('after_validate_authorization_request') + except OAuth2Error as error: + error.redirect_uri = redirect_uri + error.redirect_fragment = True + raise error + return redirect_uri + + def create_authorization_response(self, redirect_uri, grant_user): + """If the resource owner grants the access request, the authorization + server issues an access token and delivers it to the client by adding + the following parameters to the fragment component of the redirection + URI using the "application/x-www-form-urlencoded" format. + Per `Section 4.2.2`_. + + access_token + REQUIRED. The access token issued by the authorization server. + + token_type + REQUIRED. The type of the token issued as described in + Section 7.1. Value is case insensitive. + + expires_in + RECOMMENDED. The lifetime in seconds of the access token. For + example, the value "3600" denotes that the access token will + expire in one hour from the time the response was generated. + If omitted, the authorization server SHOULD provide the + expiration time via other means or document the default value. + + scope + OPTIONAL, if identical to the scope requested by the client; + otherwise, REQUIRED. The scope of the access token as + described by Section 3.3. + + state + REQUIRED if the "state" parameter was present in the client + authorization request. The exact value received from the + client. + + The authorization server MUST NOT issue a refresh token. + + For example, the authorization server redirects the user-agent by + sending the following HTTP response: + + .. code-block:: http + + HTTP/1.1 302 Found + Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA + &state=xyz&token_type=example&expires_in=3600 + + Developers should note that some user-agents do not support the + inclusion of a fragment component in the HTTP "Location" response + header field. Such clients will require using other methods for + redirecting the client than a 3xx redirection response -- for + example, returning an HTML page that includes a 'continue' button + with an action linked to the redirection URI. + + .. _`Section 4.2.2`: https://tools.ietf.org/html/rfc6749#section-4.2.2 + + :param redirect_uri: Redirect to the given URI for the authorization + :param grant_user: if resource owner granted the request, pass this + resource owner, otherwise pass None. + :returns: (status_code, body, headers) + """ + state = self.request.state + if grant_user: + self.request.user = grant_user + token = self.generate_token( + user=grant_user, + scope=self.request.scope, + include_refresh_token=False, + ) + log.debug('Grant token %r to %r', token, self.request.client) + + self.save_token(token) + self.execute_hook('process_token', token=token) + params = [(k, token[k]) for k in token] + if state: + params.append(('state', state)) + + uri = add_params_to_uri(redirect_uri, params, fragment=True) + headers = [('Location', uri)] + return 302, '', headers + else: + raise AccessDeniedError( + state=state, + redirect_uri=redirect_uri, + redirect_fragment=True + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/refresh_token.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/refresh_token.py new file mode 100644 index 0000000000000000000000000000000000000000..4df5b70e2436ca08621fee6568fee170a37360d4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/refresh_token.py @@ -0,0 +1,179 @@ +""" + authlib.oauth2.rfc6749.grants.refresh_token + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + A special grant endpoint for refresh_token grant_type. Refreshing an + Access Token per `Section 6`_. + + .. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6 +""" + +import logging +from .base import BaseGrant, TokenEndpointMixin +from ..util import scope_to_list +from ..errors import ( + InvalidRequestError, + InvalidScopeError, + InvalidGrantError, + UnauthorizedClientError, +) +log = logging.getLogger(__name__) + + +class RefreshTokenGrant(BaseGrant, TokenEndpointMixin): + """A special grant endpoint for refresh_token grant_type. Refreshing an + Access Token per `Section 6`_. + + .. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6 + """ + GRANT_TYPE = 'refresh_token' + + #: The authorization server MAY issue a new refresh token + INCLUDE_NEW_REFRESH_TOKEN = False + + def _validate_request_client(self): + # require client authentication for confidential clients or for any + # client that was issued client credentials (or with other + # authentication requirements) + client = self.authenticate_token_endpoint_client() + log.debug('Validate token request of %r', client) + + if not client.check_grant_type(self.GRANT_TYPE): + raise UnauthorizedClientError() + + return client + + def _validate_request_token(self, client): + refresh_token = self.request.form.get('refresh_token') + if refresh_token is None: + raise InvalidRequestError('Missing "refresh_token" in request.') + + token = self.authenticate_refresh_token(refresh_token) + if not token or not token.check_client(client): + raise InvalidGrantError() + return token + + def _validate_token_scope(self, token): + scope = self.request.scope + if not scope: + return + + original_scope = token.get_scope() + if not original_scope: + raise InvalidScopeError() + + original_scope = set(scope_to_list(original_scope)) + if not original_scope.issuperset(set(scope_to_list(scope))): + raise InvalidScopeError() + + def validate_token_request(self): + """If the authorization server issued a refresh token to the client, the + client makes a refresh request to the token endpoint by adding the + following parameters using the "application/x-www-form-urlencoded" + format per Appendix B with a character encoding of UTF-8 in the HTTP + request entity-body, per Section 6: + + grant_type + REQUIRED. Value MUST be set to "refresh_token". + + refresh_token + REQUIRED. The refresh token issued to the client. + + scope + OPTIONAL. The scope of the access request as described by + Section 3.3. The requested scope MUST NOT include any scope + not originally granted by the resource owner, and if omitted is + treated as equal to the scope originally granted by the + resource owner. + + + For example, the client makes the following HTTP request using + transport-layer security (with extra line breaks for display purposes + only): + + .. code-block:: http + + POST /token HTTP/1.1 + Host: server.example.com + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + Content-Type: application/x-www-form-urlencoded + + grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA + """ + client = self._validate_request_client() + self.request.client = client + refresh_token = self._validate_request_token(client) + self._validate_token_scope(refresh_token) + self.request.refresh_token = refresh_token + + def create_token_response(self): + """If valid and authorized, the authorization server issues an access + token as described in Section 5.1. If the request failed + verification or is invalid, the authorization server returns an error + response as described in Section 5.2. + """ + refresh_token = self.request.refresh_token + user = self.authenticate_user(refresh_token) + if not user: + raise InvalidRequestError('There is no "user" for this token.') + + client = self.request.client + token = self.issue_token(user, refresh_token) + log.debug('Issue token %r to %r', token, client) + + self.request.user = user + self.save_token(token) + self.execute_hook('process_token', token=token) + self.revoke_old_credential(refresh_token) + return 200, token, self.TOKEN_RESPONSE_HEADER + + def issue_token(self, user, refresh_token): + scope = self.request.scope + if not scope: + scope = refresh_token.get_scope() + + token = self.generate_token( + user=user, + scope=scope, + include_refresh_token=self.INCLUDE_NEW_REFRESH_TOKEN, + ) + return token + + def authenticate_refresh_token(self, refresh_token): + """Get token information with refresh_token string. Developers MUST + implement this method in subclass:: + + def authenticate_refresh_token(self, refresh_token): + token = Token.get(refresh_token=refresh_token) + if token and not token.refresh_token_revoked: + return token + + :param refresh_token: The refresh token issued to the client + :return: token + """ + raise NotImplementedError() + + def authenticate_user(self, refresh_token): + """Authenticate the user related to this credential. Developers MUST + implement this method in subclass:: + + def authenticate_user(self, credential): + return User.get(credential.user_id) + + :param refresh_token: Token object + :return: user + """ + raise NotImplementedError() + + def revoke_old_credential(self, refresh_token): + """The authorization server MAY revoke the old refresh token after + issuing a new refresh token to the client. Developers MUST implement + this method in subclass:: + + def revoke_old_credential(self, refresh_token): + credential.revoked = True + credential.save() + + :param refresh_token: Token object + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/resource_owner_password_credentials.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/resource_owner_password_credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..41cabb62d94ebf40a1c251613372d9f50f9fb0e3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/grants/resource_owner_password_credentials.py @@ -0,0 +1,154 @@ +import logging +from .base import BaseGrant, TokenEndpointMixin +from ..errors import ( + UnauthorizedClientError, + InvalidRequestError, +) + +log = logging.getLogger(__name__) + + +class ResourceOwnerPasswordCredentialsGrant(BaseGrant, TokenEndpointMixin): + """The resource owner password credentials grant type is suitable in + cases where the resource owner has a trust relationship with the + client, such as the device operating system or a highly privileged + + application. The authorization server should take special care when + enabling this grant type and only allow it when other flows are not + viable. + + This grant type is suitable for clients capable of obtaining the + resource owner's credentials (username and password, typically using + an interactive form). It is also used to migrate existing clients + using direct authentication schemes such as HTTP Basic or Digest + authentication to OAuth by converting the stored credentials to an + access token:: + + +----------+ + | Resource | + | Owner | + | | + +----------+ + v + | Resource Owner + (A) Password Credentials + | + v + +---------+ +---------------+ + | |>--(B)---- Resource Owner ------->| | + | | Password Credentials | Authorization | + | Client | | Server | + | |<--(C)---- Access Token ---------<| | + | | (w/ Optional Refresh Token) | | + +---------+ +---------------+ + """ + GRANT_TYPE = 'password' + + def validate_token_request(self): + """The client makes a request to the token endpoint by adding the + following parameters using the "application/x-www-form-urlencoded" + format per Appendix B with a character encoding of UTF-8 in the HTTP + request entity-body: + + grant_type + REQUIRED. Value MUST be set to "password". + + username + REQUIRED. The resource owner username. + + password + REQUIRED. The resource owner password. + + scope + OPTIONAL. The scope of the access request as described by + Section 3.3. + + If the client type is confidential or the client was issued client + credentials (or assigned other authentication requirements), the + client MUST authenticate with the authorization server as described + in Section 3.2.1. + + For example, the client makes the following HTTP request using + transport-layer security (with extra line breaks for display purposes + only): + + .. code-block:: http + + POST /token HTTP/1.1 + Host: server.example.com + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + Content-Type: application/x-www-form-urlencoded + + grant_type=password&username=johndoe&password=A3ddj3w + """ + # ignore validate for grant_type, since it is validated by + # check_token_endpoint + client = self.authenticate_token_endpoint_client() + log.debug('Validate token request of %r', client) + + if not client.check_grant_type(self.GRANT_TYPE): + raise UnauthorizedClientError() + + params = self.request.form + if 'username' not in params: + raise InvalidRequestError('Missing "username" in request.') + if 'password' not in params: + raise InvalidRequestError('Missing "password" in request.') + + log.debug('Authenticate user of %r', params['username']) + user = self.authenticate_user( + params['username'], + params['password'] + ) + if not user: + raise InvalidRequestError( + 'Invalid "username" or "password" in request.', + ) + self.request.client = client + self.request.user = user + self.validate_requested_scope() + + def create_token_response(self): + """If the access token request is valid and authorized, the + authorization server issues an access token and optional refresh + token as described in Section 5.1. If the request failed client + authentication or is invalid, the authorization server returns an + error response as described in Section 5.2. + + An example successful response: + + .. code-block:: http + + HTTP/1.1 200 OK + Content-Type: application/json + Cache-Control: no-store + Pragma: no-cache + + { + "access_token":"2YotnFZFEjr1zCsicMWpAA", + "token_type":"example", + "expires_in":3600, + "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", + "example_parameter":"example_value" + } + + :returns: (status_code, body, headers) + """ + user = self.request.user + scope = self.request.scope + token = self.generate_token(user=user, scope=scope) + log.debug('Issue token %r to %r', token, self.client) + self.save_token(token) + self.execute_hook('process_token', token=token) + return 200, token, self.TOKEN_RESPONSE_HEADER + + def authenticate_user(self, username, password): + """validate the resource owner password credentials using its + existing password validation algorithm:: + + def authenticate_user(self, username, password): + user = get_user_by_username(username) + if user.check_password(password): + return user + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/models.py new file mode 100644 index 0000000000000000000000000000000000000000..fe4922bb48281cd7d536fcaadd92588229d496cb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/models.py @@ -0,0 +1,228 @@ +""" + authlib.oauth2.rfc6749.models + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + This module defines how to construct Client, AuthorizationCode and Token. +""" +from authlib.deprecate import deprecate + + +class ClientMixin: + """Implementation of OAuth 2 Client described in `Section 2`_ with + some methods to help validation. A client has at least these information: + + * client_id: A string represents client identifier. + * client_secret: A string represents client password. + * token_endpoint_auth_method: A way to authenticate client at token + endpoint. + + .. _`Section 2`: https://tools.ietf.org/html/rfc6749#section-2 + """ + + def get_client_id(self): + """A method to return client_id of the client. For instance, the value + in database is saved in a column called ``client_id``:: + + def get_client_id(self): + return self.client_id + + :return: string + """ + raise NotImplementedError() + + def get_default_redirect_uri(self): + """A method to get client default redirect_uri. For instance, the + database table for client has a column called ``default_redirect_uri``:: + + def get_default_redirect_uri(self): + return self.default_redirect_uri + + :return: A URL string + """ + raise NotImplementedError() + + def get_allowed_scope(self, scope): + """A method to return a list of requested scopes which are supported by + this client. For instance, there is a ``scope`` column:: + + def get_allowed_scope(self, scope): + if not scope: + return '' + allowed = set(scope_to_list(self.scope)) + return list_to_scope([s for s in scope.split() if s in allowed]) + + :param scope: the requested scope. + :return: string of scope + """ + raise NotImplementedError() + + def check_redirect_uri(self, redirect_uri): + """Validate redirect_uri parameter in Authorization Endpoints. For + instance, in the client table, there is an ``allowed_redirect_uris`` + column:: + + def check_redirect_uri(self, redirect_uri): + return redirect_uri in self.allowed_redirect_uris + + :param redirect_uri: A URL string for redirecting. + :return: bool + """ + raise NotImplementedError() + + def check_client_secret(self, client_secret): + """Check client_secret matching with the client. For instance, in + the client table, the column is called ``client_secret``:: + + import secrets + + def check_client_secret(self, client_secret): + return secrets.compare_digest(self.client_secret, client_secret) + + :param client_secret: A string of client secret + :return: bool + """ + raise NotImplementedError() + + def check_endpoint_auth_method(self, method, endpoint): + """Check if client support the given method for the given endpoint. + There is a ``token_endpoint_auth_method`` defined via `RFC7591`_. + Developers MAY re-implement this method with:: + + def check_endpoint_auth_method(self, method, endpoint): + if endpoint == 'token': + # if client table has ``token_endpoint_auth_method`` + return self.token_endpoint_auth_method == method + return True + + Method values defined by this specification are: + + * "none": The client is a public client as defined in OAuth 2.0, + and does not have a client secret. + + * "client_secret_post": The client uses the HTTP POST parameters + as defined in OAuth 2.0 + + * "client_secret_basic": The client uses HTTP Basic as defined in + OAuth 2.0 + + .. _`RFC7591`: https://tools.ietf.org/html/rfc7591 + """ + raise NotImplementedError() + + def check_token_endpoint_auth_method(self, method): + deprecate('Please implement ``check_endpoint_auth_method`` instead.') + return self.check_endpoint_auth_method(method, 'token') + + def check_response_type(self, response_type): + """Validate if the client can handle the given response_type. There + are two response types defined by RFC6749: code and token. For + instance, there is a ``allowed_response_types`` column in your client:: + + def check_response_type(self, response_type): + return response_type in self.response_types + + :param response_type: the requested response_type string. + :return: bool + """ + raise NotImplementedError() + + def check_grant_type(self, grant_type): + """Validate if the client can handle the given grant_type. There are + four grant types defined by RFC6749: + + * authorization_code + * implicit + * client_credentials + * password + + For instance, there is a ``allowed_grant_types`` column in your client:: + + def check_grant_type(self, grant_type): + return grant_type in self.grant_types + + :param grant_type: the requested grant_type string. + :return: bool + """ + raise NotImplementedError() + + +class AuthorizationCodeMixin: + def get_redirect_uri(self): + """A method to get authorization code's ``redirect_uri``. + For instance, the database table for authorization code has a + column called ``redirect_uri``:: + + def get_redirect_uri(self): + return self.redirect_uri + + :return: A URL string + """ + raise NotImplementedError() + + def get_scope(self): + """A method to get scope of the authorization code. For instance, + the column is called ``scope``:: + + def get_scope(self): + return self.scope + + :return: scope string + """ + raise NotImplementedError() + + +class TokenMixin: + def check_client(self, client): + """A method to check if this token is issued to the given client. + For instance, ``client_id`` is saved on token table:: + + def check_client(self, client): + return self.client_id == client.client_id + + :return: bool + """ + raise NotImplementedError() + + def get_scope(self): + """A method to get scope of the authorization code. For instance, + the column is called ``scope``:: + + def get_scope(self): + return self.scope + + :return: scope string + """ + raise NotImplementedError() + + def get_expires_in(self): + """A method to get the ``expires_in`` value of the token. e.g. + the column is called ``expires_in``:: + + def get_expires_in(self): + return self.expires_in + + :return: timestamp int + """ + raise NotImplementedError() + + def is_expired(self): + """A method to define if this token is expired. For instance, + there is a column ``expired_at`` in the table:: + + def is_expired(self): + return self.expired_at < now + + :return: boolean + """ + raise NotImplementedError() + + def is_revoked(self): + """A method to define if this token is revoked. For instance, + there is a boolean column ``revoked`` in the table:: + + def is_revoked(self): + return self.revoked + + :return: boolean + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/parameters.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3a5aa65e2fabad6a3236ea2a0673a429b708f7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/parameters.py @@ -0,0 +1,214 @@ +from authlib.common.urls import ( + urlparse, + add_params_to_uri, + add_params_to_qs, +) +from authlib.common.encoding import to_unicode +from .errors import ( + MissingCodeException, + MissingTokenException, + MissingTokenTypeException, + MismatchingStateException, +) +from .util import list_to_scope + + +def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None, + scope=None, state=None, **kwargs): + """Prepare the authorization grant request URI. + + The client constructs the request URI by adding the following + parameters to the query component of the authorization endpoint URI + using the ``application/x-www-form-urlencoded`` format: + + :param uri: The authorize endpoint to fetch "code" or "token". + :param client_id: The client identifier as described in `Section 2.2`_. + :param response_type: To indicate which OAuth 2 grant/flow is required, + "code" and "token". + :param redirect_uri: The client provided URI to redirect back to after + authorization as described in `Section 3.1.2`_. + :param scope: The scope of the access request as described by + `Section 3.3`_. + :param state: An opaque value used by the client to maintain + state between the request and callback. The authorization + server includes this value when redirecting the user-agent + back to the client. The parameter SHOULD be used for + preventing cross-site request forgery as described in + `Section 10.12`_. + :param kwargs: Extra arguments to embed in the grant/authorization URL. + + An example of an authorization code grant authorization URL:: + + /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz + &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb + + .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 + .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + .. _`section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 + """ + params = [ + ('response_type', response_type), + ('client_id', client_id) + ] + + if redirect_uri: + params.append(('redirect_uri', redirect_uri)) + if scope: + params.append(('scope', list_to_scope(scope))) + if state: + params.append(('state', state)) + + for k in kwargs: + if kwargs[k] is not None: + params.append((to_unicode(k), kwargs[k])) + + return add_params_to_uri(uri, params) + + +def prepare_token_request(grant_type, body='', redirect_uri=None, **kwargs): + """Prepare the access token request. Per `Section 4.1.3`_. + + The client makes a request to the token endpoint by adding the + following parameters using the ``application/x-www-form-urlencoded`` + format in the HTTP request entity-body: + + :param grant_type: To indicate grant type being used, i.e. "password", + "authorization_code" or "client_credentials". + :param body: Existing request body to embed parameters in. + :param redirect_uri: If the "redirect_uri" parameter was included in the + authorization request as described in + `Section 4.1.1`_, and their values MUST be identical. + :param kwargs: Extra arguments to embed in the request body. + + An example of an authorization code token request body:: + + grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA + &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb + + .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1 + .. _`Section 4.1.3`: https://tools.ietf.org/html/rfc6749#section-4.1.3 + """ + params = [('grant_type', grant_type)] + + if redirect_uri: + params.append(('redirect_uri', redirect_uri)) + + if 'scope' in kwargs: + kwargs['scope'] = list_to_scope(kwargs['scope']) + + if grant_type == 'authorization_code' and 'code' not in kwargs: + raise MissingCodeException() + + for k in kwargs: + if kwargs[k]: + params.append((to_unicode(k), kwargs[k])) + + return add_params_to_qs(body, params) + + +def parse_authorization_code_response(uri, state=None): + """Parse authorization grant response URI into a dict. + + If the resource owner grants the access request, the authorization + server issues an authorization code and delivers it to the client by + adding the following parameters to the query component of the + redirection URI using the ``application/x-www-form-urlencoded`` format: + + **code** + REQUIRED. The authorization code generated by the + authorization server. The authorization code MUST expire + shortly after it is issued to mitigate the risk of leaks. A + maximum authorization code lifetime of 10 minutes is + RECOMMENDED. The client MUST NOT use the authorization code + more than once. If an authorization code is used more than + once, the authorization server MUST deny the request and SHOULD + revoke (when possible) all tokens previously issued based on + that authorization code. The authorization code is bound to + the client identifier and redirection URI. + + **state** + REQUIRED if the "state" parameter was present in the client + authorization request. The exact value received from the + client. + + :param uri: The full redirect URL back to the client. + :param state: The state parameter from the authorization request. + + For example, the authorization server redirects the user-agent by + sending the following HTTP response: + + .. code-block:: http + + HTTP/1.1 302 Found + Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA + &state=xyz + + """ + query = urlparse.urlparse(uri).query + params = dict(urlparse.parse_qsl(query)) + + if 'code' not in params: + raise MissingCodeException() + + params_state = params.get('state') + if state and params_state != state: + raise MismatchingStateException() + + return params + + +def parse_implicit_response(uri, state=None): + """Parse the implicit token response URI into a dict. + + If the resource owner grants the access request, the authorization + server issues an access token and delivers it to the client by adding + the following parameters to the fragment component of the redirection + URI using the ``application/x-www-form-urlencoded`` format: + + **access_token** + REQUIRED. The access token issued by the authorization server. + + **token_type** + REQUIRED. The type of the token issued as described in + Section 7.1. Value is case insensitive. + + **expires_in** + RECOMMENDED. The lifetime in seconds of the access token. For + example, the value "3600" denotes that the access token will + expire in one hour from the time the response was generated. + If omitted, the authorization server SHOULD provide the + expiration time via other means or document the default value. + + **scope** + OPTIONAL, if identical to the scope requested by the client, + otherwise REQUIRED. The scope of the access token as described + by Section 3.3. + + **state** + REQUIRED if the "state" parameter was present in the client + authorization request. The exact value received from the + client. + + Similar to the authorization code response, but with a full token provided + in the URL fragment: + + .. code-block:: http + + HTTP/1.1 302 Found + Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA + &state=xyz&token_type=example&expires_in=3600 + """ + fragment = urlparse.urlparse(uri).fragment + params = dict(urlparse.parse_qsl(fragment, keep_blank_values=True)) + + if 'access_token' not in params: + raise MissingTokenException() + + if 'token_type' not in params: + raise MissingTokenTypeException() + + if state and params.get('state', None) != state: + raise MismatchingStateException() + + return params diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/requests.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/requests.py new file mode 100644 index 0000000000000000000000000000000000000000..1c0e4859bdab829c1142e2e152e46a820304ba78 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/requests.py @@ -0,0 +1,84 @@ +from authlib.common.encoding import json_loads +from authlib.common.urls import urlparse, url_decode +from .errors import InsecureTransportError + + +class OAuth2Request: + def __init__(self, method: str, uri: str, body=None, headers=None): + InsecureTransportError.check(uri) + #: HTTP method + self.method = method + self.uri = uri + self.body = body + #: HTTP headers + self.headers = headers or {} + + self.client = None + self.auth_method = None + self.user = None + self.authorization_code = None + self.refresh_token = None + self.credential = None + + @property + def args(self): + query = urlparse.urlparse(self.uri).query + return dict(url_decode(query)) + + @property + def form(self): + return self.body or {} + + @property + def data(self): + data = {} + data.update(self.args) + data.update(self.form) + return data + + @property + def client_id(self) -> str: + """The authorization server issues the registered client a client + identifier -- a unique string representing the registration + information provided by the client. The value is extracted from + request. + + :return: string + """ + return self.data.get('client_id') + + @property + def response_type(self) -> str: + rt = self.data.get('response_type') + if rt and ' ' in rt: + # sort multiple response types + return ' '.join(sorted(rt.split())) + return rt + + @property + def grant_type(self) -> str: + return self.form.get('grant_type') + + @property + def redirect_uri(self): + return self.data.get('redirect_uri') + + @property + def scope(self) -> str: + return self.data.get('scope') + + @property + def state(self): + return self.data.get('state') + + +class JsonRequest: + def __init__(self, method, uri, body=None, headers=None): + self.method = method + self.uri = uri + self.body = body + self.headers = headers or {} + + @property + def data(self): + return json_loads(self.body) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/resource_protector.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/resource_protector.py new file mode 100644 index 0000000000000000000000000000000000000000..60a85d800efb0ba84e1318cd2470b7e5a31887c4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/resource_protector.py @@ -0,0 +1,140 @@ +""" + authlib.oauth2.rfc6749.resource_protector + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Implementation of Accessing Protected Resources per `Section 7`_. + + .. _`Section 7`: https://tools.ietf.org/html/rfc6749#section-7 +""" +from .util import scope_to_list +from .errors import MissingAuthorizationError, UnsupportedTokenTypeError + + +class TokenValidator: + """Base token validator class. Subclass this validator to register + into ResourceProtector instance. + """ + TOKEN_TYPE = 'bearer' + + def __init__(self, realm=None, **extra_attributes): + self.realm = realm + self.extra_attributes = extra_attributes + + @staticmethod + def scope_insufficient(token_scopes, required_scopes): + if not required_scopes: + return False + + token_scopes = scope_to_list(token_scopes) + if not token_scopes: + return True + + token_scopes = set(token_scopes) + for scope in required_scopes: + resource_scopes = set(scope_to_list(scope)) + if token_scopes.issuperset(resource_scopes): + return False + + return True + + def authenticate_token(self, token_string): + """A method to query token from database with the given token string. + Developers MUST re-implement this method. For instance:: + + def authenticate_token(self, token_string): + return get_token_from_database(token_string) + + :param token_string: A string to represent the access_token. + :return: token + """ + raise NotImplementedError() + + def validate_request(self, request): + """A method to validate if the HTTP request is valid or not. Developers MUST + re-implement this method. For instance, your server requires a + "X-Device-Version" in the header:: + + def validate_request(self, request): + if 'X-Device-Version' not in request.headers: + raise InvalidRequestError() + + Usually, you don't have to detect if the request is valid or not. If you have + to, you MUST re-implement this method. + + :param request: instance of HttpRequest + :raise: InvalidRequestError + """ + + def validate_token(self, token, scopes, request): + """A method to validate if the authorized token is valid, if it has the + permission on the given scopes. Developers MUST re-implement this method. + e.g, check if token is expired, revoked:: + + def validate_token(self, token, scopes, request): + if not token: + raise InvalidTokenError() + if token.is_expired() or token.is_revoked(): + raise InvalidTokenError() + if not match_token_scopes(token, scopes): + raise InsufficientScopeError() + """ + raise NotImplementedError() + + +class ResourceProtector: + def __init__(self): + self._token_validators = {} + self._default_realm = None + self._default_auth_type = None + + def register_token_validator(self, validator: TokenValidator): + """Register a token validator for a given Authorization type. + Authlib has a built-in BearerTokenValidator per rfc6750. + """ + if not self._default_auth_type: + self._default_realm = validator.realm + self._default_auth_type = validator.TOKEN_TYPE + + if validator.TOKEN_TYPE not in self._token_validators: + self._token_validators[validator.TOKEN_TYPE] = validator + + def get_token_validator(self, token_type): + """Get token validator from registry for the given token type.""" + validator = self._token_validators.get(token_type.lower()) + if not validator: + raise UnsupportedTokenTypeError(self._default_auth_type, self._default_realm) + return validator + + def parse_request_authorization(self, request): + """Parse the token and token validator from request Authorization header. + Here is an example of Authorization header:: + + Authorization: Bearer a-token-string + + This method will parse this header, if it can find the validator for + ``Bearer``, it will return the validator and ``a-token-string``. + + :return: validator, token_string + :raise: MissingAuthorizationError + :raise: UnsupportedTokenTypeError + """ + auth = request.headers.get('Authorization') + if not auth: + raise MissingAuthorizationError(self._default_auth_type, self._default_realm) + + # https://tools.ietf.org/html/rfc6749#section-7.1 + token_parts = auth.split(None, 1) + if len(token_parts) != 2: + raise UnsupportedTokenTypeError(self._default_auth_type, self._default_realm) + + token_type, token_string = token_parts + validator = self.get_token_validator(token_type) + return validator, token_string + + def validate_request(self, scopes, request, **kwargs): + """Validate the request and return a token.""" + validator, token_string = self.parse_request_authorization(request) + validator.validate_request(request) + token = validator.authenticate_token(token_string) + validator.validate_token(token, scopes, request, **kwargs) + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/token_endpoint.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/token_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..0ede557f662d8c9f8e42f7f0dcbdee15c150a1b1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/token_endpoint.py @@ -0,0 +1,32 @@ +class TokenEndpoint: + #: Endpoint name to be registered + ENDPOINT_NAME = None + #: Supported token types + SUPPORTED_TOKEN_TYPES = ('access_token', 'refresh_token') + #: Allowed client authenticate methods + CLIENT_AUTH_METHODS = ['client_secret_basic'] + + def __init__(self, server): + self.server = server + + def __call__(self, request): + # make it callable for authorization server + # ``create_endpoint_response`` + return self.create_endpoint_response(request) + + def create_endpoint_request(self, request): + return self.server.create_oauth2_request(request) + + def authenticate_endpoint_client(self, request): + """Authentication client for endpoint with ``CLIENT_AUTH_METHODS``. + """ + client = self.server.authenticate_client( + request, self.CLIENT_AUTH_METHODS, self.ENDPOINT_NAME) + request.client = client + return client + + def authenticate_token(self, request, client): + raise NotImplementedError() + + def create_endpoint_response(self, request): + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/util.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/util.py new file mode 100644 index 0000000000000000000000000000000000000000..a216fbf343bba5ac892605486f704f4eea298826 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/util.py @@ -0,0 +1,40 @@ +import base64 +import binascii +from authlib.common.encoding import to_unicode + + +def list_to_scope(scope): + """Convert a list of scopes to a space separated string.""" + if isinstance(scope, (set, tuple, list)): + return " ".join([to_unicode(s) for s in scope]) + if scope is None: + return scope + return to_unicode(scope) + + +def scope_to_list(scope): + """Convert a space separated string to a list of scopes.""" + if isinstance(scope, (tuple, list, set)): + return [to_unicode(s) for s in scope] + elif scope is None: + return None + return scope.strip().split() + + +def extract_basic_authorization(headers): + auth = headers.get('Authorization') + if not auth or ' ' not in auth: + return None, None + + auth_type, auth_token = auth.split(None, 1) + if auth_type.lower() != 'basic': + return None, None + + try: + query = to_unicode(base64.b64decode(auth_token)) + except (binascii.Error, TypeError): + return None, None + if ':' in query: + username, password = query.split(':', 1) + return username, password + return query, None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/wrappers.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..2ecf82485bc51b323872c381d4e4f1a09b436c56 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6749/wrappers.py @@ -0,0 +1,23 @@ +import time + + +class OAuth2Token(dict): + def __init__(self, params): + if params.get('expires_at'): + params['expires_at'] = int(params['expires_at']) + elif params.get('expires_in'): + params['expires_at'] = int(time.time()) + \ + int(params['expires_in']) + super().__init__(params) + + def is_expired(self): + expires_at = self.get('expires_at') + if not expires_at: + return None + return expires_at < time.time() + + @classmethod + def from_dict(cls, token): + if isinstance(token, dict) and not isinstance(token, cls): + token = cls(token) + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef3880ba4bffaeeacccc24aa5bbaca6a8b3365fb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/__init__.py @@ -0,0 +1,26 @@ +""" + authlib.oauth2.rfc6750 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + The OAuth 2.0 Authorization Framework: Bearer Token Usage. + + https://tools.ietf.org/html/rfc6750 +""" + +from .errors import InvalidTokenError, InsufficientScopeError +from .parameters import add_bearer_token +from .token import BearerTokenGenerator +from .validator import BearerTokenValidator + +# TODO: add deprecation +BearerToken = BearerTokenGenerator + + +__all__ = [ + 'InvalidTokenError', 'InsufficientScopeError', + 'add_bearer_token', + 'BearerToken', + 'BearerTokenGenerator', + 'BearerTokenValidator', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/errors.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..1be92a3587921a53ee13b2b663737f35813b1557 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/errors.py @@ -0,0 +1,80 @@ +""" + authlib.rfc6750.errors + ~~~~~~~~~~~~~~~~~~~~~~ + + OAuth Extensions Error Registration. When a request fails, + the resource server responds using the appropriate HTTP + status code and includes one of the following error codes + in the response. + + https://tools.ietf.org/html/rfc6750#section-6.2 + + :copyright: (c) 2017 by Hsiaoming Yang. +""" +from ..base import OAuth2Error + +__all__ = [ + 'InvalidTokenError', 'InsufficientScopeError' +] + + +class InvalidTokenError(OAuth2Error): + """The access token provided is expired, revoked, malformed, or + invalid for other reasons. The resource SHOULD respond with + the HTTP 401 (Unauthorized) status code. The client MAY + request a new access token and retry the protected resource + request. + + https://tools.ietf.org/html/rfc6750#section-3.1 + """ + error = 'invalid_token' + description = ( + 'The access token provided is expired, revoked, malformed, ' + 'or invalid for other reasons.' + ) + status_code = 401 + + def __init__(self, description=None, uri=None, status_code=None, + state=None, realm=None, **extra_attributes): + super().__init__( + description, uri, status_code, state) + self.realm = realm + self.extra_attributes = extra_attributes + + def get_headers(self): + """If the protected resource request does not include authentication + credentials or does not contain an access token that enables access + to the protected resource, the resource server MUST include the HTTP + "WWW-Authenticate" response header field; it MAY include it in + response to other conditions as well. + + https://tools.ietf.org/html/rfc6750#section-3 + """ + headers = super().get_headers() + + extras = [] + if self.realm: + extras.append(f'realm="{self.realm}"') + if self.extra_attributes: + extras.extend([f'{k}="{self.extra_attributes[k]}"' for k in self.extra_attributes]) + extras.append(f'error="{self.error}"') + error_description = self.get_error_description() + extras.append(f'error_description="{error_description}"') + headers.append( + ('WWW-Authenticate', 'Bearer ' + ', '.join(extras)) + ) + return headers + + +class InsufficientScopeError(OAuth2Error): + """The request requires higher privileges than provided by the + access token. The resource server SHOULD respond with the HTTP + 403 (Forbidden) status code and MAY include the "scope" + attribute with the scope necessary to access the protected + resource. + + https://tools.ietf.org/html/rfc6750#section-3.1 + """ + error = 'insufficient_scope' + description = 'The request requires higher privileges than provided by the access token.' + status_code = 403 diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/parameters.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..8914a909684f1b5abbe61382c9a812a44f71aee7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/parameters.py @@ -0,0 +1,41 @@ +from authlib.common.urls import add_params_to_qs, add_params_to_uri + + +def add_to_uri(token, uri): + """Add a Bearer Token to the request URI. + Not recommended, use only if client can't use authorization header or body. + + http://www.example.com/path?access_token=h480djs93hd8 + """ + return add_params_to_uri(uri, [('access_token', token)]) + + +def add_to_headers(token, headers=None): + """Add a Bearer Token to the request URI. + Recommended method of passing bearer tokens. + + Authorization: Bearer h480djs93hd8 + """ + headers = headers or {} + headers['Authorization'] = f'Bearer {token}' + return headers + + +def add_to_body(token, body=None): + """Add a Bearer Token to the request body. + + access_token=h480djs93hd8 + """ + if body is None: + body = '' + return add_params_to_qs(body, [('access_token', token)]) + + +def add_bearer_token(token, uri, headers, body, placement='header'): + if placement in ('uri', 'url', 'query'): + uri = add_to_uri(token, uri) + elif placement in ('header', 'headers'): + headers = add_to_headers(token, headers) + elif placement == 'body': + body = add_to_body(token, body) + return uri, headers, body diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/token.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/token.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab4dc5b28718e61747d99f98dbabdcb77c7dfb5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/token.py @@ -0,0 +1,88 @@ +class BearerTokenGenerator: + """Bearer token generator which can create the payload for token response + by OAuth 2 server. A typical token response would be: + + .. code-block:: http + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + Cache-Control: no-store + Pragma: no-cache + + { + "access_token":"mF_9.B5f-4.1JqM", + "token_type":"Bearer", + "expires_in":3600, + "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA" + } + """ + + #: default expires_in value + DEFAULT_EXPIRES_IN = 3600 + #: default expires_in value differentiate by grant_type + GRANT_TYPES_EXPIRES_IN = { + 'authorization_code': 864000, + 'implicit': 3600, + 'password': 864000, + 'client_credentials': 864000 + } + + def __init__(self, access_token_generator, + refresh_token_generator=None, + expires_generator=None): + self.access_token_generator = access_token_generator + self.refresh_token_generator = refresh_token_generator + self.expires_generator = expires_generator + + def _get_expires_in(self, client, grant_type): + if self.expires_generator is None: + expires_in = self.GRANT_TYPES_EXPIRES_IN.get( + grant_type, self.DEFAULT_EXPIRES_IN) + elif callable(self.expires_generator): + expires_in = self.expires_generator(client, grant_type) + elif isinstance(self.expires_generator, int): + expires_in = self.expires_generator + else: + expires_in = self.DEFAULT_EXPIRES_IN + return expires_in + + @staticmethod + def get_allowed_scope(client, scope): + if scope: + scope = client.get_allowed_scope(scope) + return scope + + def generate(self, grant_type, client, user=None, scope=None, + expires_in=None, include_refresh_token=True): + """Generate a bearer token for OAuth 2.0 authorization token endpoint. + + :param client: the client that making the request. + :param grant_type: current requested grant_type. + :param user: current authorized user. + :param expires_in: if provided, use this value as expires_in. + :param scope: current requested scope. + :param include_refresh_token: should refresh_token be included. + :return: Token dict + """ + scope = self.get_allowed_scope(client, scope) + access_token = self.access_token_generator( + client=client, grant_type=grant_type, user=user, scope=scope) + if expires_in is None: + expires_in = self._get_expires_in(client, grant_type) + + token = { + 'token_type': 'Bearer', + 'access_token': access_token, + } + if expires_in: + token['expires_in'] = expires_in + if include_refresh_token and self.refresh_token_generator: + token['refresh_token'] = self.refresh_token_generator( + client=client, grant_type=grant_type, user=user, scope=scope) + if scope: + token['scope'] = scope + return token + + def __call__(self, grant_type, client, user=None, scope=None, + expires_in=None, include_refresh_token=True): + return self.generate(grant_type, client, user, scope, expires_in, include_refresh_token) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/validator.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/validator.py new file mode 100644 index 0000000000000000000000000000000000000000..d47901451368cccb06a5197e87011ad05befbe8c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc6750/validator.py @@ -0,0 +1,39 @@ +""" + authlib.oauth2.rfc6750.validator + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Validate Bearer Token for in request, scope and token. +""" + +from ..rfc6749 import TokenValidator +from .errors import ( + InvalidTokenError, + InsufficientScopeError +) + + +class BearerTokenValidator(TokenValidator): + TOKEN_TYPE = 'bearer' + + def authenticate_token(self, token_string): + """A method to query token from database with the given token string. + Developers MUST re-implement this method. For instance:: + + def authenticate_token(self, token_string): + return get_token_from_database(token_string) + + :param token_string: A string to represent the access_token. + :return: token + """ + raise NotImplementedError() + + def validate_token(self, token, scopes, request): + """Check if token is active and matches the requested scopes.""" + if not token: + raise InvalidTokenError(realm=self.realm, extra_attributes=self.extra_attributes) + if token.is_expired(): + raise InvalidTokenError(realm=self.realm, extra_attributes=self.extra_attributes) + if token.is_revoked(): + raise InvalidTokenError(realm=self.realm, extra_attributes=self.extra_attributes) + if self.scope_insufficient(token.get_scope(), scopes): + raise InsufficientScopeError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7009/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7009/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9c120258f184b3b3b248ffb9fdbba0a0472d7e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7009/__init__.py @@ -0,0 +1,14 @@ +""" + authlib.oauth2.rfc7009 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + OAuth 2.0 Token Revocation. + + https://tools.ietf.org/html/rfc7009 +""" + +from .parameters import prepare_revoke_token_request +from .revocation import RevocationEndpoint + +__all__ = ['prepare_revoke_token_request', 'RevocationEndpoint'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7009/parameters.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7009/parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..2a829a752f05fff66625dd6a7d011f68224077fb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7009/parameters.py @@ -0,0 +1,25 @@ +from authlib.common.urls import add_params_to_qs + + +def prepare_revoke_token_request(token, token_type_hint=None, + body=None, headers=None): + """Construct request body and headers for revocation endpoint. + + :param token: access_token or refresh_token string. + :param token_type_hint: Optional, `access_token` or `refresh_token`. + :param body: current request body. + :param headers: current request headers. + :return: tuple of (body, headers) + + https://tools.ietf.org/html/rfc7009#section-2.1 + """ + params = [('token', token)] + if token_type_hint: + params.append(('token_type_hint', token_type_hint)) + + body = add_params_to_qs(body or '', params) + if headers is None: + headers = {} + + headers['Content-Type'] = 'application/x-www-form-urlencoded' + return body, headers diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7009/revocation.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7009/revocation.py new file mode 100644 index 0000000000000000000000000000000000000000..f0984789f1e2a910b721a39a551eb9ffe392fc91 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7009/revocation.py @@ -0,0 +1,108 @@ +from authlib.consts import default_json_headers +from ..rfc6749 import TokenEndpoint +from ..rfc6749 import ( + InvalidRequestError, + UnsupportedTokenTypeError, +) + + +class RevocationEndpoint(TokenEndpoint): + """Implementation of revocation endpoint which is described in + `RFC7009`_. + + .. _RFC7009: https://tools.ietf.org/html/rfc7009 + """ + #: Endpoint name to be registered + ENDPOINT_NAME = 'revocation' + + def authenticate_token(self, request, client): + """The client constructs the request by including the following + parameters using the "application/x-www-form-urlencoded" format in + the HTTP request entity-body: + + token + REQUIRED. The token that the client wants to get revoked. + + token_type_hint + OPTIONAL. A hint about the type of the token submitted for + revocation. + """ + self.check_params(request, client) + token = self.query_token(request.form['token'], request.form.get('token_type_hint')) + if token and token.check_client(client): + return token + + def check_params(self, request, client): + if 'token' not in request.form: + raise InvalidRequestError() + + hint = request.form.get('token_type_hint') + if hint and hint not in self.SUPPORTED_TOKEN_TYPES: + raise UnsupportedTokenTypeError() + + def create_endpoint_response(self, request): + """Validate revocation request and create the response for revocation. + For example, a client may request the revocation of a refresh token + with the following request:: + + POST /revoke HTTP/1.1 + Host: server.example.com + Content-Type: application/x-www-form-urlencoded + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + + token=45ghiukldjahdnhzdauz&token_type_hint=refresh_token + + :returns: (status_code, body, headers) + """ + # The authorization server first validates the client credentials + client = self.authenticate_endpoint_client(request) + + # then verifies whether the token was issued to the client making + # the revocation request + token = self.authenticate_token(request, client) + + # the authorization server invalidates the token + if token: + self.revoke_token(token, request) + self.server.send_signal( + 'after_revoke_token', + token=token, + client=client, + ) + return 200, {}, default_json_headers + + def query_token(self, token_string, token_type_hint): + """Get the token from database/storage by the given token string. + Developers should implement this method:: + + def query_token(self, token_string, token_type_hint): + if token_type_hint == 'access_token': + return Token.query_by_access_token(token_string) + if token_type_hint == 'refresh_token': + return Token.query_by_refresh_token(token_string) + return Token.query_by_access_token(token_string) or \ + Token.query_by_refresh_token(token_string) + """ + raise NotImplementedError() + + def revoke_token(self, token, request): + """Mark token as revoked. Since token MUST be unique, it would be + dangerous to delete it. Consider this situation: + + 1. Jane obtained a token XYZ + 2. Jane revoked (deleted) token XYZ + 3. Bob generated a new token XYZ + 4. Jane can use XYZ to access Bob's resource + + It would be secure to mark a token as revoked:: + + def revoke_token(self, token, request): + hint = request.form.get('token_type_hint') + if hint == 'access_token': + token.access_token_revoked = True + else: + token.access_token_revoked = True + token.refresh_token_revoked = True + token.save() + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7521/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7521/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0dbe0b30b0de7819ed718708351901cff9156bf1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7521/__init__.py @@ -0,0 +1,3 @@ +from .client import AssertionClient + +__all__ = ['AssertionClient'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7521/client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7521/client.py new file mode 100644 index 0000000000000000000000000000000000000000..e7ce2c3c77caad23002cf6210606c6c2492b18df --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7521/client.py @@ -0,0 +1,91 @@ +from authlib.common.encoding import to_native +from authlib.oauth2.base import OAuth2Error + + +class AssertionClient: + """Constructs a new Assertion Framework for OAuth 2.0 Authorization Grants + per RFC7521_. + + .. _RFC7521: https://tools.ietf.org/html/rfc7521 + """ + DEFAULT_GRANT_TYPE = None + ASSERTION_METHODS = {} + token_auth_class = None + oauth_error_class = OAuth2Error + + def __init__(self, session, token_endpoint, issuer, subject, + audience=None, grant_type=None, claims=None, + token_placement='header', scope=None, **kwargs): + + self.session = session + + if audience is None: + audience = token_endpoint + + self.token_endpoint = token_endpoint + + if grant_type is None: + grant_type = self.DEFAULT_GRANT_TYPE + + self.grant_type = grant_type + + # https://tools.ietf.org/html/rfc7521#section-5.1 + self.issuer = issuer + self.subject = subject + self.audience = audience + self.claims = claims + self.scope = scope + if self.token_auth_class is not None: + self.token_auth = self.token_auth_class(None, token_placement, self) + self._kwargs = kwargs + + @property + def token(self): + return self.token_auth.token + + @token.setter + def token(self, token): + self.token_auth.set_token(token) + + def refresh_token(self): + """Using Assertions as Authorization Grants to refresh token as + described in `Section 4.1`_. + + .. _`Section 4.1`: https://tools.ietf.org/html/rfc7521#section-4.1 + """ + generate_assertion = self.ASSERTION_METHODS[self.grant_type] + assertion = generate_assertion( + issuer=self.issuer, + subject=self.subject, + audience=self.audience, + claims=self.claims, + **self._kwargs + ) + data = { + 'assertion': to_native(assertion), + 'grant_type': self.grant_type, + } + if self.scope: + data['scope'] = self.scope + + return self._refresh_token(data) + + def parse_response_token(self, resp): + if resp.status_code >= 500: + resp.raise_for_status() + + token = resp.json() + if 'error' in token: + raise self.oauth_error_class( + error=token['error'], + description=token.get('error_description') + ) + + self.token = token + return self.token + + def _refresh_token(self, data): + resp = self.session.request( + 'POST', self.token_endpoint, data=data, withhold_token=True) + + return self.parse_response_token(resp) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9d3d32a9d3b16d117891012155956fc01cd7b4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/__init__.py @@ -0,0 +1,37 @@ +""" + authlib.oauth2.rfc7523 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + JSON Web Token (JWT) Profile for OAuth 2.0 Client + Authentication and Authorization Grants. + + https://tools.ietf.org/html/rfc7523 +""" + +from .jwt_bearer import JWTBearerGrant +from .client import ( + JWTBearerClientAssertion, +) +from .assertion import ( + client_secret_jwt_sign, + private_key_jwt_sign, +) +from .auth import ( + ClientSecretJWT, PrivateKeyJWT, +) +from .token import JWTBearerTokenGenerator +from .validator import JWTBearerToken, JWTBearerTokenValidator + +__all__ = [ + 'JWTBearerGrant', + 'JWTBearerClientAssertion', + 'client_secret_jwt_sign', + 'private_key_jwt_sign', + 'ClientSecretJWT', + 'PrivateKeyJWT', + + 'JWTBearerToken', + 'JWTBearerTokenGenerator', + 'JWTBearerTokenValidator', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/assertion.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/assertion.py new file mode 100644 index 0000000000000000000000000000000000000000..0bb9fe7be71d1684ba793074f0a4df6786830b76 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/assertion.py @@ -0,0 +1,66 @@ +import time +from authlib.jose import jwt +from authlib.common.security import generate_token + + +def sign_jwt_bearer_assertion( + key, issuer, audience, subject=None, issued_at=None, + expires_at=None, claims=None, header=None, **kwargs): + + if header is None: + header = {} + alg = kwargs.pop('alg', None) + if alg: + header['alg'] = alg + if 'alg' not in header: + raise ValueError('Missing "alg" in header') + + payload = {'iss': issuer, 'aud': audience} + + # subject is not required in Google service + if subject: + payload['sub'] = subject + + if not issued_at: + issued_at = int(time.time()) + + expires_in = kwargs.pop('expires_in', 3600) + if not expires_at: + expires_at = issued_at + expires_in + + payload['iat'] = issued_at + payload['exp'] = expires_at + + if claims: + payload.update(claims) + + return jwt.encode(header, payload, key) + + +def client_secret_jwt_sign(client_secret, client_id, token_endpoint, alg='HS256', + claims=None, **kwargs): + return _sign(client_secret, client_id, token_endpoint, alg, claims, **kwargs) + + +def private_key_jwt_sign(private_key, client_id, token_endpoint, alg='RS256', + claims=None, **kwargs): + return _sign(private_key, client_id, token_endpoint, alg, claims, **kwargs) + + +def _sign(key, client_id, token_endpoint, alg, claims=None, **kwargs): + # REQUIRED. Issuer. This MUST contain the client_id of the OAuth Client. + issuer = client_id + # REQUIRED. Subject. This MUST contain the client_id of the OAuth Client. + subject = client_id + # The Audience SHOULD be the URL of the Authorization Server's Token Endpoint. + audience = token_endpoint + + # jti is required + if claims is None: + claims = {} + if 'jti' not in claims: + claims['jti'] = generate_token(36) + + return sign_jwt_bearer_assertion( + key=key, issuer=issuer, audience=audience, subject=subject, + claims=claims, alg=alg, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/auth.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..776446674bf4aa5283b0ea6e96b73819a6570f17 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/auth.py @@ -0,0 +1,94 @@ +from authlib.common.urls import add_params_to_qs +from .assertion import client_secret_jwt_sign, private_key_jwt_sign +from .client import ASSERTION_TYPE + + +class ClientSecretJWT: + """Authentication method for OAuth 2.0 Client. This authentication + method is called ``client_secret_jwt``, which is using ``client_id`` + and ``client_secret`` constructed with JWT to identify a client. + + Here is an example of use ``client_secret_jwt`` with Requests Session:: + + from authlib.integrations.requests_client import OAuth2Session + + token_endpoint = 'https://example.com/oauth/token' + session = OAuth2Session( + 'your-client-id', 'your-client-secret', + token_endpoint_auth_method='client_secret_jwt' + ) + session.register_client_auth_method(ClientSecretJWT(token_endpoint)) + session.fetch_token(token_endpoint) + + :param token_endpoint: A string URL of the token endpoint + :param claims: Extra JWT claims + :param headers: Extra JWT headers + :param alg: ``alg`` value, default is HS256 + """ + name = 'client_secret_jwt' + alg = 'HS256' + + def __init__(self, token_endpoint=None, claims=None, headers=None, alg=None): + self.token_endpoint = token_endpoint + self.claims = claims + self.headers = headers + if alg is not None: + self.alg = alg + + def sign(self, auth, token_endpoint): + return client_secret_jwt_sign( + auth.client_secret, + client_id=auth.client_id, + token_endpoint=token_endpoint, + claims=self.claims, + header=self.headers, + alg=self.alg, + ) + + def __call__(self, auth, method, uri, headers, body): + token_endpoint = self.token_endpoint + if not token_endpoint: + token_endpoint = uri + + client_assertion = self.sign(auth, token_endpoint) + body = add_params_to_qs(body or '', [ + ('client_assertion_type', ASSERTION_TYPE), + ('client_assertion', client_assertion) + ]) + return uri, headers, body + + +class PrivateKeyJWT(ClientSecretJWT): + """Authentication method for OAuth 2.0 Client. This authentication + method is called ``private_key_jwt``, which is using ``client_id`` + and ``private_key`` constructed with JWT to identify a client. + + Here is an example of use ``private_key_jwt`` with Requests Session:: + + from authlib.integrations.requests_client import OAuth2Session + + token_endpoint = 'https://example.com/oauth/token' + session = OAuth2Session( + 'your-client-id', 'your-client-private-key', + token_endpoint_auth_method='private_key_jwt' + ) + session.register_client_auth_method(PrivateKeyJWT(token_endpoint)) + session.fetch_token(token_endpoint) + + :param token_endpoint: A string URL of the token endpoint + :param claims: Extra JWT claims + :param headers: Extra JWT headers + :param alg: ``alg`` value, default is RS256 + """ + name = 'private_key_jwt' + alg = 'RS256' + + def sign(self, auth, token_endpoint): + return private_key_jwt_sign( + auth.client_secret, + client_id=auth.client_id, + token_endpoint=token_endpoint, + claims=self.claims, + header=self.headers, + alg=self.alg, + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/client.py new file mode 100644 index 0000000000000000000000000000000000000000..2a6a1bfcf9fea1e849d5105c9921833641577c11 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/client.py @@ -0,0 +1,113 @@ +import logging +from authlib.jose import jwt +from authlib.jose.errors import JoseError +from ..rfc6749 import InvalidClientError + +ASSERTION_TYPE = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer' +log = logging.getLogger(__name__) + + +class JWTBearerClientAssertion: + """Implementation of Using JWTs for Client Authentication, which is + defined by RFC7523. + """ + #: Value of ``client_assertion_type`` of JWTs + CLIENT_ASSERTION_TYPE = ASSERTION_TYPE + #: Name of the client authentication method + CLIENT_AUTH_METHOD = 'client_assertion_jwt' + + def __init__(self, token_url, validate_jti=True): + self.token_url = token_url + self._validate_jti = validate_jti + + def __call__(self, query_client, request): + data = request.form + assertion_type = data.get('client_assertion_type') + assertion = data.get('client_assertion') + if assertion_type == ASSERTION_TYPE and assertion: + resolve_key = self.create_resolve_key_func(query_client, request) + self.process_assertion_claims(assertion, resolve_key) + return self.authenticate_client(request.client) + log.debug('Authenticate via %r failed', self.CLIENT_AUTH_METHOD) + + def create_claims_options(self): + """Create a claims_options for verify JWT payload claims. Developers + MAY overwrite this method to create a more strict options.""" + # https://tools.ietf.org/html/rfc7523#section-3 + # The Audience SHOULD be the URL of the Authorization Server's Token Endpoint + options = { + 'iss': {'essential': True, 'validate': _validate_iss}, + 'sub': {'essential': True}, + 'aud': {'essential': True, 'value': self.token_url}, + 'exp': {'essential': True}, + } + if self._validate_jti: + options['jti'] = {'essential': True, 'validate': self.validate_jti} + return options + + def process_assertion_claims(self, assertion, resolve_key): + """Extract JWT payload claims from request "assertion", per + `Section 3.1`_. + + :param assertion: assertion string value in the request + :param resolve_key: function to resolve the sign key + :return: JWTClaims + :raise: InvalidClientError + + .. _`Section 3.1`: https://tools.ietf.org/html/rfc7523#section-3.1 + """ + try: + claims = jwt.decode( + assertion, resolve_key, + claims_options=self.create_claims_options() + ) + claims.validate() + except JoseError as e: + log.debug('Assertion Error: %r', e) + raise InvalidClientError() + return claims + + def authenticate_client(self, client): + if client.check_endpoint_auth_method(self.CLIENT_AUTH_METHOD, 'token'): + return client + raise InvalidClientError() + + def create_resolve_key_func(self, query_client, request): + def resolve_key(headers, payload): + # https://tools.ietf.org/html/rfc7523#section-3 + # For client authentication, the subject MUST be the + # "client_id" of the OAuth client + client_id = payload['sub'] + client = query_client(client_id) + if not client: + raise InvalidClientError() + request.client = client + return self.resolve_client_public_key(client, headers) + return resolve_key + + def validate_jti(self, claims, jti): + """Validate if the given ``jti`` value is used before. Developers + MUST implement this method:: + + def validate_jti(self, claims, jti): + key = 'jti:{}-{}'.format(claims['sub'], jti) + if redis.get(key): + return False + redis.set(key, 1, ex=3600) + return True + """ + raise NotImplementedError() + + def resolve_client_public_key(self, client, headers): + """Resolve the client public key for verifying the JWT signature. + A client may have many public keys, in this case, we can retrieve it + via ``kid`` value in headers. Developers MUST implement this method:: + + def resolve_client_public_key(self, client, headers): + return client.public_key + """ + raise NotImplementedError() + + +def _validate_iss(claims, iss): + return claims['sub'] == iss diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/jwt_bearer.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/jwt_bearer.py new file mode 100644 index 0000000000000000000000000000000000000000..fb672a9231676ef4f51cd782c97d6b123b77d5a5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/jwt_bearer.py @@ -0,0 +1,182 @@ +import logging +from authlib.jose import jwt, JoseError +from ..rfc6749 import BaseGrant, TokenEndpointMixin +from ..rfc6749 import ( + UnauthorizedClientError, + InvalidRequestError, + InvalidGrantError, + InvalidClientError, +) +from .assertion import sign_jwt_bearer_assertion + +log = logging.getLogger(__name__) +JWT_BEARER_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer' + + +class JWTBearerGrant(BaseGrant, TokenEndpointMixin): + GRANT_TYPE = JWT_BEARER_GRANT_TYPE + + #: Options for verifying JWT payload claims. Developers MAY + #: overwrite this constant to create a more strict options. + CLAIMS_OPTIONS = { + 'iss': {'essential': True}, + 'aud': {'essential': True}, + 'exp': {'essential': True}, + } + + @staticmethod + def sign(key, issuer, audience, subject=None, + issued_at=None, expires_at=None, claims=None, **kwargs): + return sign_jwt_bearer_assertion( + key, issuer, audience, subject, issued_at, + expires_at, claims, **kwargs) + + def process_assertion_claims(self, assertion): + """Extract JWT payload claims from request "assertion", per + `Section 3.1`_. + + :param assertion: assertion string value in the request + :return: JWTClaims + :raise: InvalidGrantError + + .. _`Section 3.1`: https://tools.ietf.org/html/rfc7523#section-3.1 + """ + try: + claims = jwt.decode( + assertion, self.resolve_public_key, + claims_options=self.CLAIMS_OPTIONS) + claims.validate() + except JoseError as e: + log.debug('Assertion Error: %r', e) + raise InvalidGrantError(description=e.description) + return claims + + def resolve_public_key(self, headers, payload): + client = self.resolve_issuer_client(payload['iss']) + return self.resolve_client_key(client, headers, payload) + + def validate_token_request(self): + """The client makes a request to the token endpoint by sending the + following parameters using the "application/x-www-form-urlencoded" + format per `Section 2.1`_: + + grant_type + REQUIRED. Value MUST be set to + "urn:ietf:params:oauth:grant-type:jwt-bearer". + + assertion + REQUIRED. Value MUST contain a single JWT. + + scope + OPTIONAL. + + The following example demonstrates an access token request with a JWT + as an authorization grant: + + .. code-block:: http + + POST /token.oauth2 HTTP/1.1 + Host: as.example.com + Content-Type: application/x-www-form-urlencoded + + grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer + &assertion=eyJhbGciOiJFUzI1NiIsImtpZCI6IjE2In0. + eyJpc3Mi[...omitted for brevity...]. + J9l-ZhwP[...omitted for brevity...] + + .. _`Section 2.1`: https://tools.ietf.org/html/rfc7523#section-2.1 + """ + assertion = self.request.form.get('assertion') + if not assertion: + raise InvalidRequestError('Missing "assertion" in request') + + claims = self.process_assertion_claims(assertion) + client = self.resolve_issuer_client(claims['iss']) + log.debug('Validate token request of %s', client) + + if not client.check_grant_type(self.GRANT_TYPE): + raise UnauthorizedClientError() + + self.request.client = client + self.validate_requested_scope() + + subject = claims.get('sub') + if subject: + user = self.authenticate_user(subject) + if not user: + raise InvalidGrantError(description='Invalid "sub" value in assertion') + + log.debug('Check client(%s) permission to User(%s)', client, user) + if not self.has_granted_permission(client, user): + raise InvalidClientError( + description='Client has no permission to access user data') + self.request.user = user + + def create_token_response(self): + """If valid and authorized, the authorization server issues an access + token. + """ + token = self.generate_token( + scope=self.request.scope, + user=self.request.user, + include_refresh_token=False, + ) + log.debug('Issue token %r to %r', token, self.request.client) + self.save_token(token) + return 200, token, self.TOKEN_RESPONSE_HEADER + + def resolve_issuer_client(self, issuer): + """Fetch client via "iss" in assertion claims. Developers MUST + implement this method in subclass, e.g.:: + + def resolve_issuer_client(self, issuer): + return Client.query_by_iss(issuer) + + :param issuer: "iss" value in assertion + :return: Client instance + """ + raise NotImplementedError() + + def resolve_client_key(self, client, headers, payload): + """Resolve client key to decode assertion data. Developers MUST + implement this method in subclass. For instance, there is a + "jwks" column on client table, e.g.:: + + def resolve_client_key(self, client, headers, payload): + # from authlib.jose import JsonWebKey + + key_set = JsonWebKey.import_key_set(client.jwks) + return key_set.find_by_kid(headers['kid']) + + :param client: instance of OAuth client model + :param headers: headers part of the JWT + :param payload: payload part of the JWT + :return: ``authlib.jose.Key`` instance + """ + raise NotImplementedError() + + def authenticate_user(self, subject): + """Authenticate user with the given assertion claims. Developers MUST + implement it in subclass, e.g.:: + + def authenticate_user(self, subject): + return User.get_by_sub(subject) + + :param subject: "sub" value in claims + :return: User instance + """ + raise NotImplementedError() + + def has_granted_permission(self, client, user): + """Check if the client has permission to access the given user's resource. + Developers MUST implement it in subclass, e.g.:: + + def has_granted_permission(self, client, user): + permission = ClientUserGrant.query(client=client, user=user) + return permission.granted + + :param client: instance of OAuth client model + :param user: instance of User model + :return: bool + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/token.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/token.py new file mode 100644 index 0000000000000000000000000000000000000000..27fab5f4ceee1c073e6c1a3222783a96115b0b38 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/token.py @@ -0,0 +1,93 @@ +import time +from authlib.common.encoding import to_native +from authlib.jose import jwt + + +class JWTBearerTokenGenerator: + """A JSON Web Token formatted bearer token generator for jwt-bearer grant type. + This token generator can be registered into authorization server:: + + authorization_server.register_token_generator( + 'urn:ietf:params:oauth:grant-type:jwt-bearer', + JWTBearerTokenGenerator(private_rsa_key), + ) + + In this way, we can generate the token into JWT format. And we don't have to + save this token into database, since it will be short time valid. Consider to + rewrite ``JWTBearerGrant.save_token``:: + + class MyJWTBearerGrant(JWTBearerGrant): + def save_token(self, token): + pass + + :param secret_key: private RSA key in bytes, JWK or JWK Set. + :param issuer: a string or URI of the issuer + :param alg: ``alg`` to use in JWT + """ + DEFAULT_EXPIRES_IN = 3600 + + def __init__(self, secret_key, issuer=None, alg='RS256'): + self.secret_key = secret_key + self.issuer = issuer + self.alg = alg + + @staticmethod + def get_allowed_scope(client, scope): + if scope: + scope = client.get_allowed_scope(scope) + return scope + + @staticmethod + def get_sub_value(user): + """Return user's ID as ``sub`` value in token payload. For instance:: + + @staticmethod + def get_sub_value(user): + return str(user.id) + """ + return user.get_user_id() + + def get_token_data(self, grant_type, client, expires_in, user=None, scope=None): + scope = self.get_allowed_scope(client, scope) + issued_at = int(time.time()) + data = { + 'scope': scope, + 'grant_type': grant_type, + 'iat': issued_at, + 'exp': issued_at + expires_in, + 'client_id': client.get_client_id(), + } + if self.issuer: + data['iss'] = self.issuer + if user: + data['sub'] = self.get_sub_value(user) + return data + + def generate(self, grant_type, client, user=None, scope=None, expires_in=None): + """Generate a bearer token for OAuth 2.0 authorization token endpoint. + + :param client: the client that making the request. + :param grant_type: current requested grant_type. + :param user: current authorized user. + :param expires_in: if provided, use this value as expires_in. + :param scope: current requested scope. + :return: Token dict + """ + if not expires_in: + expires_in = self.DEFAULT_EXPIRES_IN + + token_data = self.get_token_data(grant_type, client, expires_in, user, scope) + access_token = jwt.encode({'alg': self.alg}, token_data, key=self.secret_key, check=False) + token = { + 'token_type': 'Bearer', + 'access_token': to_native(access_token), + 'expires_in': expires_in + } + if scope: + token['scope'] = scope + return token + + def __call__(self, grant_type, client, user=None, scope=None, + expires_in=None, include_refresh_token=True): + # there is absolutely no refresh token in JWT format + return self.generate(grant_type, client, user, scope, expires_in) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/validator.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/validator.py new file mode 100644 index 0000000000000000000000000000000000000000..f2423b8a10ec5bb03a0dc359e809a88263db29c5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7523/validator.py @@ -0,0 +1,54 @@ +import time +import logging +from authlib.jose import jwt, JoseError, JWTClaims +from ..rfc6749 import TokenMixin +from ..rfc6750 import BearerTokenValidator + +logger = logging.getLogger(__name__) + + +class JWTBearerToken(TokenMixin, JWTClaims): + def check_client(self, client): + return self['client_id'] == client.get_client_id() + + def get_scope(self): + return self.get('scope') + + def get_expires_in(self): + return self['exp'] - self['iat'] + + def is_expired(self): + return self['exp'] < time.time() + + def is_revoked(self): + return False + + +class JWTBearerTokenValidator(BearerTokenValidator): + TOKEN_TYPE = 'bearer' + token_cls = JWTBearerToken + + def __init__(self, public_key, issuer=None, realm=None, **extra_attributes): + super().__init__(realm, **extra_attributes) + self.public_key = public_key + claims_options = { + 'exp': {'essential': True}, + 'client_id': {'essential': True}, + 'grant_type': {'essential': True}, + } + if issuer: + claims_options['iss'] = {'essential': True, 'value': issuer} + self.claims_options = claims_options + + def authenticate_token(self, token_string): + try: + claims = jwt.decode( + token_string, self.public_key, + claims_options=self.claims_options, + claims_cls=self.token_cls, + ) + claims.validate() + return claims + except JoseError as error: + logger.debug('Authenticate token failed. %r', error) + return None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ebb07096524af996335f1b4c63d618590a56b6b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/__init__.py @@ -0,0 +1,25 @@ +""" + authlib.oauth2.rfc7591 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + OAuth 2.0 Dynamic Client Registration Protocol. + + https://tools.ietf.org/html/rfc7591 +""" + + +from .claims import ClientMetadataClaims +from .endpoint import ClientRegistrationEndpoint +from .errors import ( + InvalidRedirectURIError, + InvalidClientMetadataError, + InvalidSoftwareStatementError, + UnapprovedSoftwareStatementError, +) + +__all__ = [ + 'ClientMetadataClaims', 'ClientRegistrationEndpoint', + 'InvalidRedirectURIError', 'InvalidClientMetadataError', + 'InvalidSoftwareStatementError', 'UnapprovedSoftwareStatementError', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/claims.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/claims.py new file mode 100644 index 0000000000000000000000000000000000000000..b6157b520c60d66ae212adf4c9b38825bc240ab8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/claims.py @@ -0,0 +1,218 @@ +from authlib.jose import BaseClaims, JsonWebKey +from authlib.jose.errors import InvalidClaimError +from authlib.common.urls import is_valid_url + + +class ClientMetadataClaims(BaseClaims): + # https://tools.ietf.org/html/rfc7591#section-2 + REGISTERED_CLAIMS = [ + 'redirect_uris', + 'token_endpoint_auth_method', + 'grant_types', + 'response_types', + 'client_name', + 'client_uri', + 'logo_uri', + 'scope', + 'contacts', + 'tos_uri', + 'policy_uri', + 'jwks_uri', + 'jwks', + 'software_id', + 'software_version', + ] + + def validate(self): + self._validate_essential_claims() + self.validate_redirect_uris() + self.validate_token_endpoint_auth_method() + self.validate_grant_types() + self.validate_response_types() + self.validate_client_name() + self.validate_client_uri() + self.validate_logo_uri() + self.validate_scope() + self.validate_contacts() + self.validate_tos_uri() + self.validate_policy_uri() + self.validate_jwks_uri() + self.validate_jwks() + self.validate_software_id() + self.validate_software_version() + + def validate_redirect_uris(self): + """Array of redirection URI strings for use in redirect-based flows + such as the authorization code and implicit flows. As required by + Section 2 of OAuth 2.0 [RFC6749], clients using flows with + redirection MUST register their redirection URI values. + Authorization servers that support dynamic registration for + redirect-based flows MUST implement support for this metadata + value. + """ + uris = self.get('redirect_uris') + if uris: + for uri in uris: + self._validate_uri('redirect_uris', uri) + + def validate_token_endpoint_auth_method(self): + """String indicator of the requested authentication method for the + token endpoint. + """ + # If unspecified or omitted, the default is "client_secret_basic" + if 'token_endpoint_auth_method' not in self: + self['token_endpoint_auth_method'] = 'client_secret_basic' + self._validate_claim_value('token_endpoint_auth_method') + + def validate_grant_types(self): + """Array of OAuth 2.0 grant type strings that the client can use at + the token endpoint. + """ + self._validate_claim_value('grant_types') + + def validate_response_types(self): + """Array of the OAuth 2.0 response type strings that the client can + use at the authorization endpoint. + """ + self._validate_claim_value('response_types') + + def validate_client_name(self): + """Human-readable string name of the client to be presented to the + end-user during authorization. If omitted, the authorization + server MAY display the raw "client_id" value to the end-user + instead. It is RECOMMENDED that clients always send this field. + The value of this field MAY be internationalized, as described in + Section 2.2. + """ + + def validate_client_uri(self): + """URL string of a web page providing information about the client. + If present, the server SHOULD display this URL to the end-user in + a clickable fashion. It is RECOMMENDED that clients always send + this field. The value of this field MUST point to a valid web + page. The value of this field MAY be internationalized, as + described in Section 2.2. + """ + self._validate_uri('client_uri') + + def validate_logo_uri(self): + """URL string that references a logo for the client. If present, the + server SHOULD display this image to the end-user during approval. + The value of this field MUST point to a valid image file. The + value of this field MAY be internationalized, as described in + Section 2.2. + """ + self._validate_uri('logo_uri') + + def validate_scope(self): + """String containing a space-separated list of scope values (as + described in Section 3.3 of OAuth 2.0 [RFC6749]) that the client + can use when requesting access tokens. The semantics of values in + this list are service specific. If omitted, an authorization + server MAY register a client with a default set of scopes. + """ + self._validate_claim_value('scope') + + def validate_contacts(self): + """Array of strings representing ways to contact people responsible + for this client, typically email addresses. The authorization + server MAY make these contact addresses available to end-users for + support requests for the client. See Section 6 for information on + Privacy Considerations. + """ + if 'contacts' in self and not isinstance(self['contacts'], list): + raise InvalidClaimError('contacts') + + def validate_tos_uri(self): + """URL string that points to a human-readable terms of service + document for the client that describes a contractual relationship + between the end-user and the client that the end-user accepts when + authorizing the client. The authorization server SHOULD display + this URL to the end-user if it is provided. The value of this + field MUST point to a valid web page. The value of this field MAY + be internationalized, as described in Section 2.2. + """ + self._validate_uri('tos_uri') + + def validate_policy_uri(self): + """URL string that points to a human-readable privacy policy document + that describes how the deployment organization collects, uses, + retains, and discloses personal data. The authorization server + SHOULD display this URL to the end-user if it is provided. The + value of this field MUST point to a valid web page. The value of + this field MAY be internationalized, as described in Section 2.2. + """ + self._validate_uri('policy_uri') + + def validate_jwks_uri(self): + """URL string referencing the client's JSON Web Key (JWK) Set + [RFC7517] document, which contains the client's public keys. The + value of this field MUST point to a valid JWK Set document. These + keys can be used by higher-level protocols that use signing or + encryption. For instance, these keys might be used by some + applications for validating signed requests made to the token + endpoint when using JWTs for client authentication [RFC7523]. Use + of this parameter is preferred over the "jwks" parameter, as it + allows for easier key rotation. The "jwks_uri" and "jwks" + parameters MUST NOT both be present in the same request or + response. + """ + # TODO: use real HTTP library + self._validate_uri('jwks_uri') + + def validate_jwks(self): + """Client's JSON Web Key Set [RFC7517] document value, which contains + the client's public keys. The value of this field MUST be a JSON + object containing a valid JWK Set. These keys can be used by + higher-level protocols that use signing or encryption. This + parameter is intended to be used by clients that cannot use the + "jwks_uri" parameter, such as native clients that cannot host + public URLs. The "jwks_uri" and "jwks" parameters MUST NOT both + be present in the same request or response. + """ + if 'jwks' in self: + if 'jwks_uri' in self: + # The "jwks_uri" and "jwks" parameters MUST NOT both be present + raise InvalidClaimError('jwks') + + jwks = self['jwks'] + try: + key_set = JsonWebKey.import_key_set(jwks) + if not key_set: + raise InvalidClaimError('jwks') + except ValueError: + raise InvalidClaimError('jwks') + + def validate_software_id(self): + """A unique identifier string (e.g., a Universally Unique Identifier + (UUID)) assigned by the client developer or software publisher + used by registration endpoints to identify the client software to + be dynamically registered. Unlike "client_id", which is issued by + the authorization server and SHOULD vary between instances, the + "software_id" SHOULD remain the same for all instances of the + client software. The "software_id" SHOULD remain the same across + multiple updates or versions of the same piece of software. The + value of this field is not intended to be human readable and is + usually opaque to the client and authorization server. + """ + + def validate_software_version(self): + """A version identifier string for the client software identified by + "software_id". The value of the "software_version" SHOULD change + on any update to the client software identified by the same + "software_id". The value of this field is intended to be compared + using string equality matching and no other comparison semantics + are defined by this specification. The value of this field is + outside the scope of this specification, but it is not intended to + be human readable and is usually opaque to the client and + authorization server. The definition of what constitutes an + update to client software that would trigger a change to this + value is specific to the software itself and is outside the scope + of this specification. + """ + + def _validate_uri(self, key, uri=None): + if uri is None: + uri = self.get(key) + if uri and not is_valid_url(uri): + raise InvalidClaimError(key) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/endpoint.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..d26e06145899d27eaca987bc1dab87791d4e1186 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/endpoint.py @@ -0,0 +1,211 @@ +import os +import time +import binascii +from authlib.consts import default_json_headers +from authlib.common.security import generate_token +from authlib.jose import JsonWebToken, JoseError +from ..rfc6749 import AccessDeniedError, InvalidRequestError +from ..rfc6749 import scope_to_list +from .claims import ClientMetadataClaims +from .errors import ( + InvalidClientMetadataError, + UnapprovedSoftwareStatementError, + InvalidSoftwareStatementError, +) + + +class ClientRegistrationEndpoint: + """The client registration endpoint is an OAuth 2.0 endpoint designed to + allow a client to be registered with the authorization server. + """ + ENDPOINT_NAME = 'client_registration' + + #: The claims validation class + claims_class = ClientMetadataClaims + + #: Rewrite this value with a list to support ``software_statement`` + #: e.g. ``software_statement_alg_values_supported = ['RS256']`` + software_statement_alg_values_supported = None + + def __init__(self, server): + self.server = server + + def __call__(self, request): + return self.create_registration_response(request) + + def create_registration_response(self, request): + token = self.authenticate_token(request) + if not token: + raise AccessDeniedError() + + request.credential = token + + client_metadata = self.extract_client_metadata(request) + client_info = self.generate_client_info() + body = {} + body.update(client_metadata) + body.update(client_info) + client = self.save_client(client_info, client_metadata, request) + registration_info = self.generate_client_registration_info(client, request) + if registration_info: + body.update(registration_info) + return 201, body, default_json_headers + + def extract_client_metadata(self, request): + if not request.data: + raise InvalidRequestError() + + json_data = request.data.copy() + software_statement = json_data.pop('software_statement', None) + if software_statement and self.software_statement_alg_values_supported: + data = self.extract_software_statement(software_statement, request) + json_data.update(data) + + options = self.get_claims_options() + claims = self.claims_class(json_data, {}, options, self.get_server_metadata()) + try: + claims.validate() + except JoseError as error: + raise InvalidClientMetadataError(error.description) + return claims.get_registered_claims() + + def extract_software_statement(self, software_statement, request): + key = self.resolve_public_key(request) + if not key: + raise UnapprovedSoftwareStatementError() + + try: + jwt = JsonWebToken(self.software_statement_alg_values_supported) + claims = jwt.decode(software_statement, key) + # there is no need to validate claims + return claims + except JoseError: + raise InvalidSoftwareStatementError() + + def get_claims_options(self): + """Generate claims options validation from Authorization Server metadata.""" + metadata = self.get_server_metadata() + if not metadata: + return {} + + scopes_supported = metadata.get('scopes_supported') + response_types_supported = metadata.get('response_types_supported') + grant_types_supported = metadata.get('grant_types_supported') + auth_methods_supported = metadata.get('token_endpoint_auth_methods_supported') + options = {} + if scopes_supported is not None: + scopes_supported = set(scopes_supported) + + def _validate_scope(claims, value): + if not value: + return True + scopes = set(scope_to_list(value)) + return scopes_supported.issuperset(scopes) + + options['scope'] = {'validate': _validate_scope} + + if response_types_supported is not None: + response_types_supported = set(response_types_supported) + + def _validate_response_types(claims, value): + # If omitted, the default is that the client will use only the "code" + # response type. + response_types = set(value) if value else {"code"} + return response_types_supported.issuperset(response_types) + + options['response_types'] = {'validate': _validate_response_types} + + if grant_types_supported is not None: + grant_types_supported = set(grant_types_supported) + + def _validate_grant_types(claims, value): + # If omitted, the default behavior is that the client will use only + # the "authorization_code" Grant Type. + grant_types = set(value) if value else {"authorization_code"} + return grant_types_supported.issuperset(grant_types) + + options['grant_types'] = {'validate': _validate_grant_types} + + if auth_methods_supported is not None: + options['token_endpoint_auth_method'] = {'values': auth_methods_supported} + + return options + + def generate_client_info(self): + # https://tools.ietf.org/html/rfc7591#section-3.2.1 + client_id = self.generate_client_id() + client_secret = self.generate_client_secret() + client_id_issued_at = int(time.time()) + client_secret_expires_at = 0 + return dict( + client_id=client_id, + client_secret=client_secret, + client_id_issued_at=client_id_issued_at, + client_secret_expires_at=client_secret_expires_at, + ) + + def generate_client_registration_info(self, client, request): + """Generate ```registration_client_uri`` and ``registration_access_token`` + for RFC7592. This method returns ``None`` by default. Developers MAY rewrite + this method to return registration information.""" + return None + + def create_endpoint_request(self, request): + return self.server.create_json_request(request) + + def generate_client_id(self): + """Generate ``client_id`` value. Developers MAY rewrite this method + to use their own way to generate ``client_id``. + """ + return generate_token(42) + + def generate_client_secret(self): + """Generate ``client_secret`` value. Developers MAY rewrite this method + to use their own way to generate ``client_secret``. + """ + return binascii.hexlify(os.urandom(24)).decode('ascii') + + def get_server_metadata(self): + """Return server metadata which includes supported grant types, + response types and etc. + """ + raise NotImplementedError() + + def authenticate_token(self, request): + """Authenticate current credential who is requesting to register a client. + Developers MUST implement this method in subclass:: + + def authenticate_token(self, request): + auth = request.headers.get('Authorization') + return get_token_by_auth(auth) + + :return: token instance + """ + raise NotImplementedError() + + def resolve_public_key(self, request): + """Resolve a public key for decoding ``software_statement``. If + ``enable_software_statement=True``, developers MUST implement this + method in subclass:: + + def resolve_public_key(self, request): + return get_public_key_from_user(request.credential) + + :return: JWK or Key string + """ + raise NotImplementedError() + + def save_client(self, client_info, client_metadata, request): + """Save client into database. Developers MUST implement this method + in subclass:: + + def save_client(self, client_info, client_metadata, request): + client = OAuthClient( + client_id=client_info['client_id'], + client_secret=client_info['client_secret'], + ... + ) + client.save() + return client + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/errors.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..31693c0475070222285256b76a146f0580c4c8f3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7591/errors.py @@ -0,0 +1,33 @@ +from ..rfc6749 import OAuth2Error + + +class InvalidRedirectURIError(OAuth2Error): + """The value of one or more redirection URIs is invalid. + https://tools.ietf.org/html/rfc7591#section-3.2.2 + """ + error = 'invalid_redirect_uri' + + +class InvalidClientMetadataError(OAuth2Error): + """The value of one of the client metadata fields is invalid and the + server has rejected this request. Note that an authorization + server MAY choose to substitute a valid value for any requested + parameter of a client's metadata. + https://tools.ietf.org/html/rfc7591#section-3.2.2 + """ + error = 'invalid_client_metadata' + + +class InvalidSoftwareStatementError(OAuth2Error): + """The software statement presented is invalid. + https://tools.ietf.org/html/rfc7591#section-3.2.2 + """ + error = 'invalid_software_statement' + + +class UnapprovedSoftwareStatementError(OAuth2Error): + """The software statement presented is not approved for use by this + authorization server. + https://tools.ietf.org/html/rfc7591#section-3.2.2 + """ + error = 'unapproved_software_statement' diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7592/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7592/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6a6457be59def8756f15a43a942403e8135c08a3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7592/__init__.py @@ -0,0 +1,13 @@ +""" + authlib.oauth2.rfc7592 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + OAuth 2.0 Dynamic Client Registration Management Protocol. + + https://tools.ietf.org/html/rfc7592 +""" + +from .endpoint import ClientConfigurationEndpoint + +__all__ = ['ClientConfigurationEndpoint'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7592/endpoint.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7592/endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..cec9aad1e29496f686b917aed3dfecf4c0de84dd --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7592/endpoint.py @@ -0,0 +1,256 @@ +from authlib.consts import default_json_headers +from authlib.jose import JoseError +from ..rfc7591.claims import ClientMetadataClaims +from ..rfc6749 import scope_to_list +from ..rfc6749 import AccessDeniedError +from ..rfc6749 import InvalidClientError +from ..rfc6749 import InvalidRequestError +from ..rfc6749 import UnauthorizedClientError +from ..rfc7591 import InvalidClientMetadataError + + +class ClientConfigurationEndpoint: + ENDPOINT_NAME = 'client_configuration' + + #: The claims validation class + claims_class = ClientMetadataClaims + + def __init__(self, server): + self.server = server + + def __call__(self, request): + return self.create_configuration_response(request) + + def create_configuration_response(self, request): + # This request is authenticated by the registration access token issued + # to the client. + token = self.authenticate_token(request) + if not token: + raise AccessDeniedError() + + request.credential = token + + client = self.authenticate_client(request) + if not client: + # If the client does not exist on this server, the server MUST respond + # with HTTP 401 Unauthorized and the registration access token used to + # make this request SHOULD be immediately revoked. + self.revoke_access_token(request, token) + raise InvalidClientError(status_code=401) + + if not self.check_permission(client, request): + # If the client does not have permission to read its record, the server + # MUST return an HTTP 403 Forbidden. + raise UnauthorizedClientError(status_code=403) + + request.client = client + + if request.method == 'GET': + return self.create_read_client_response(client, request) + elif request.method == 'DELETE': + return self.create_delete_client_response(client, request) + elif request.method == 'PUT': + return self.create_update_client_response(client, request) + + def create_endpoint_request(self, request): + return self.server.create_json_request(request) + + def create_read_client_response(self, client, request): + body = self.introspect_client(client) + body.update(self.generate_client_registration_info(client, request)) + return 200, body, default_json_headers + + def create_delete_client_response(self, client, request): + self.delete_client(client, request) + headers = [ + ('Cache-Control', 'no-store'), + ('Pragma', 'no-cache'), + ] + return 204, '', headers + + def create_update_client_response(self, client, request): + # The updated client metadata fields request MUST NOT include the + # 'registration_access_token', 'registration_client_uri', + # 'client_secret_expires_at', or 'client_id_issued_at' fields + must_not_include = ( + 'registration_access_token', + 'registration_client_uri', + 'client_secret_expires_at', + 'client_id_issued_at', + ) + for k in must_not_include: + if k in request.data: + raise InvalidRequestError() + + # The client MUST include its 'client_id' field in the request + client_id = request.data.get('client_id') + if not client_id: + raise InvalidRequestError() + if client_id != client.get_client_id(): + raise InvalidRequestError() + + # If the client includes the 'client_secret' field in the request, + # the value of this field MUST match the currently issued client + # secret for that client. + if 'client_secret' in request.data: + if not client.check_client_secret(request.data['client_secret']): + raise InvalidRequestError() + + client_metadata = self.extract_client_metadata(request) + client = self.update_client(client, client_metadata, request) + return self.create_read_client_response(client, request) + + def extract_client_metadata(self, request): + json_data = request.data.copy() + options = self.get_claims_options() + claims = self.claims_class(json_data, {}, options, self.get_server_metadata()) + + try: + claims.validate() + except JoseError as error: + raise InvalidClientMetadataError(error.description) + return claims.get_registered_claims() + + def get_claims_options(self): + metadata = self.get_server_metadata() + if not metadata: + return {} + + scopes_supported = metadata.get('scopes_supported') + response_types_supported = metadata.get('response_types_supported') + grant_types_supported = metadata.get('grant_types_supported') + auth_methods_supported = metadata.get('token_endpoint_auth_methods_supported') + options = {} + if scopes_supported is not None: + scopes_supported = set(scopes_supported) + + def _validate_scope(claims, value): + if not value: + return True + scopes = set(scope_to_list(value)) + return scopes_supported.issuperset(scopes) + + options['scope'] = {'validate': _validate_scope} + + if response_types_supported is not None: + response_types_supported = set(response_types_supported) + + def _validate_response_types(claims, value): + return response_types_supported.issuperset(set(value)) + + options['response_types'] = {'validate': _validate_response_types} + + if grant_types_supported is not None: + grant_types_supported = set(grant_types_supported) + + def _validate_grant_types(claims, value): + return grant_types_supported.issuperset(set(value)) + + options['grant_types'] = {'validate': _validate_grant_types} + + if auth_methods_supported is not None: + options['token_endpoint_auth_method'] = {'values': auth_methods_supported} + + return options + + def introspect_client(self, client): + return {**client.client_info, **client.client_metadata} + + def generate_client_registration_info(self, client, request): + """Generate ```registration_client_uri`` and ``registration_access_token`` + for RFC7592. By default this method returns the values sent in the current + request. Developers MUST rewrite this method to return different registration + information.:: + + def generate_client_registration_info(self, client, request):{ + access_token = request.headers['Authorization'].split(' ')[1] + return { + 'registration_client_uri': request.uri, + 'registration_access_token': access_token, + } + + :param client: the instance of OAuth client + :param request: formatted request instance + """ + raise NotImplementedError() + + def authenticate_token(self, request): + """Authenticate current credential who is requesting to register a client. + Developers MUST implement this method in subclass:: + + def authenticate_token(self, request): + auth = request.headers.get('Authorization') + return get_token_by_auth(auth) + + :return: token instance + """ + raise NotImplementedError() + + def authenticate_client(self, request): + """Read a client from the request payload. + Developers MUST implement this method in subclass:: + + def authenticate_client(self, request): + client_id = request.data.get('client_id') + return Client.get(client_id=client_id) + + :return: client instance + """ + raise NotImplementedError() + + def revoke_access_token(self, token, request): + """Revoke a token access in case an invalid client has been requested. + Developers MUST implement this method in subclass:: + + def revoke_access_token(self, token, request): + token.revoked = True + token.save() + + """ + raise NotImplementedError() + + def check_permission(self, client, request): + """Checks wether the current client is allowed to be accessed, edited + or deleted. Developers MUST implement it in subclass, e.g.:: + + def check_permission(self, client, request): + return client.editable + + :return: boolean + """ + raise NotImplementedError() + + def delete_client(self, client, request): + """Delete authorization code from database or cache. Developers MUST + implement it in subclass, e.g.:: + + def delete_client(self, client, request): + client.delete() + + :param client: the instance of OAuth client + :param request: formatted request instance + """ + raise NotImplementedError() + + def update_client(self, client, client_metadata, request): + """Update the client in the database. Developers MUST implement this method + in subclass:: + + def update_client(self, client, client_metadata, request): + client.set_client_metadata({**client.client_metadata, **client_metadata}) + client.save() + return client + + :param client: the instance of OAuth client + :param client_metadata: a dict of the client claims to update + :param request: formatted request instance + :return: client instance + """ + + raise NotImplementedError() + + def get_server_metadata(self): + """Return server metadata which includes supported grant types, + response types and etc. + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7636/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7636/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c03043bdfabbf087d127aa3be180c4f9a2476566 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7636/__init__.py @@ -0,0 +1,13 @@ +""" + authlib.oauth2.rfc7636 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + Proof Key for Code Exchange by OAuth Public Clients. + + https://tools.ietf.org/html/rfc7636 +""" + +from .challenge import CodeChallenge, create_s256_code_challenge + +__all__ = ['CodeChallenge', 'create_s256_code_challenge'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7636/challenge.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7636/challenge.py new file mode 100644 index 0000000000000000000000000000000000000000..8303092e4bf31fa9800025880a7ec0ac073ee487 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7636/challenge.py @@ -0,0 +1,138 @@ +import re +import hashlib +from authlib.common.encoding import to_bytes, to_unicode, urlsafe_b64encode +from ..rfc6749 import ( + InvalidRequestError, + InvalidGrantError, + OAuth2Request, +) + + +CODE_VERIFIER_PATTERN = re.compile(r'^[a-zA-Z0-9\-._~]{43,128}$') + + +def create_s256_code_challenge(code_verifier): + """Create S256 code_challenge with the given code_verifier.""" + data = hashlib.sha256(to_bytes(code_verifier, 'ascii')).digest() + return to_unicode(urlsafe_b64encode(data)) + + +def compare_plain_code_challenge(code_verifier, code_challenge): + # If the "code_challenge_method" from Section 4.3 was "plain", + # they are compared directly + return code_verifier == code_challenge + + +def compare_s256_code_challenge(code_verifier, code_challenge): + # BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) == code_challenge + return create_s256_code_challenge(code_verifier) == code_challenge + + +class CodeChallenge: + """CodeChallenge extension to Authorization Code Grant. It is used to + improve the security of Authorization Code flow for public clients by + sending extra "code_challenge" and "code_verifier" to the authorization + server. + + The AuthorizationCodeGrant SHOULD save the ``code_challenge`` and + ``code_challenge_method`` into database when ``save_authorization_code``. + Then register this extension via:: + + server.register_grant( + AuthorizationCodeGrant, + [CodeChallenge(required=True)] + ) + """ + #: defaults to "plain" if not present in the request + DEFAULT_CODE_CHALLENGE_METHOD = 'plain' + #: supported ``code_challenge_method`` + SUPPORTED_CODE_CHALLENGE_METHOD = ['plain', 'S256'] + + CODE_CHALLENGE_METHODS = { + 'plain': compare_plain_code_challenge, + 'S256': compare_s256_code_challenge, + } + + def __init__(self, required=True): + self.required = required + + def __call__(self, grant): + grant.register_hook( + 'after_validate_authorization_request', + self.validate_code_challenge, + ) + grant.register_hook( + 'after_validate_token_request', + self.validate_code_verifier, + ) + + def validate_code_challenge(self, grant): + request: OAuth2Request = grant.request + challenge = request.data.get('code_challenge') + method = request.data.get('code_challenge_method') + if not challenge and not method: + return + + if not challenge: + raise InvalidRequestError('Missing "code_challenge"') + + if method and method not in self.SUPPORTED_CODE_CHALLENGE_METHOD: + raise InvalidRequestError('Unsupported "code_challenge_method"') + + def validate_code_verifier(self, grant): + request: OAuth2Request = grant.request + verifier = request.form.get('code_verifier') + + # public client MUST verify code challenge + if self.required and request.auth_method == 'none' and not verifier: + raise InvalidRequestError('Missing "code_verifier"') + + authorization_code = request.authorization_code + challenge = self.get_authorization_code_challenge(authorization_code) + + # ignore, it is the normal RFC6749 authorization_code request + if not challenge and not verifier: + return + + # challenge exists, code_verifier is required + if not verifier: + raise InvalidRequestError('Missing "code_verifier"') + + if not CODE_VERIFIER_PATTERN.match(verifier): + raise InvalidRequestError('Invalid "code_verifier"') + + # 4.6. Server Verifies code_verifier before Returning the Tokens + method = self.get_authorization_code_challenge_method(authorization_code) + if method is None: + method = self.DEFAULT_CODE_CHALLENGE_METHOD + + func = self.CODE_CHALLENGE_METHODS.get(method) + if not func: + raise RuntimeError(f'No verify method for "{method}"') + + # If the values are not equal, an error response indicating + # "invalid_grant" MUST be returned. + if not func(verifier, challenge): + raise InvalidGrantError(description='Code challenge failed.') + + def get_authorization_code_challenge(self, authorization_code): + """Get "code_challenge" associated with this authorization code. + Developers MAY re-implement it in subclass, the default logic:: + + def get_authorization_code_challenge(self, authorization_code): + return authorization_code.code_challenge + + :param authorization_code: the instance of authorization_code + """ + return authorization_code.code_challenge + + def get_authorization_code_challenge_method(self, authorization_code): + """Get "code_challenge_method" associated with this authorization code. + Developers MAY re-implement it in subclass, the default logic:: + + def get_authorization_code_challenge_method(self, authorization_code): + return authorization_code.code_challenge_method + + :param authorization_code: the instance of authorization_code + """ + return authorization_code.code_challenge_method diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..045aeda5057580b66327c4a5e43e83bdcd5863a3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/__init__.py @@ -0,0 +1,15 @@ +""" + authlib.oauth2.rfc7662 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + OAuth 2.0 Token Introspection. + + https://tools.ietf.org/html/rfc7662 +""" + +from .introspection import IntrospectionEndpoint +from .models import IntrospectionToken +from .token_validator import IntrospectTokenValidator + +__all__ = ['IntrospectionEndpoint', 'IntrospectionToken', 'IntrospectTokenValidator'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/introspection.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/introspection.py new file mode 100644 index 0000000000000000000000000000000000000000..515d6ca6b2023cec9247840877538964a6549b2b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/introspection.py @@ -0,0 +1,131 @@ +from authlib.consts import default_json_headers +from ..rfc6749 import ( + TokenEndpoint, + InvalidRequestError, + UnsupportedTokenTypeError, +) + + +class IntrospectionEndpoint(TokenEndpoint): + """Implementation of introspection endpoint which is described in + `RFC7662`_. + + .. _RFC7662: https://tools.ietf.org/html/rfc7662 + """ + #: Endpoint name to be registered + ENDPOINT_NAME = 'introspection' + + def authenticate_token(self, request, client): + """The protected resource calls the introspection endpoint using an HTTP + ``POST`` request with parameters sent as + "application/x-www-form-urlencoded" data. The protected resource sends a + parameter representing the token along with optional parameters + representing additional context that is known by the protected resource + to aid the authorization server in its response. + + token + **REQUIRED** The string value of the token. For access tokens, this + is the ``access_token`` value returned from the token endpoint + defined in OAuth 2.0. For refresh tokens, this is the + ``refresh_token`` value returned from the token endpoint as defined + in OAuth 2.0. + + token_type_hint + **OPTIONAL** A hint about the type of the token submitted for + introspection. + """ + + self.check_params(request, client) + token = self.query_token(request.form['token'], request.form.get('token_type_hint')) + if token and self.check_permission(token, client, request): + return token + + def check_params(self, request, client): + params = request.form + if 'token' not in params: + raise InvalidRequestError() + + hint = params.get('token_type_hint') + if hint and hint not in self.SUPPORTED_TOKEN_TYPES: + raise UnsupportedTokenTypeError() + + def create_endpoint_response(self, request): + """Validate introspection request and create the response. + + :returns: (status_code, body, headers) + """ + # The authorization server first validates the client credentials + client = self.authenticate_endpoint_client(request) + + # then verifies whether the token was issued to the client making + # the revocation request + token = self.authenticate_token(request, client) + + # the authorization server invalidates the token + body = self.create_introspection_payload(token) + return 200, body, default_json_headers + + def create_introspection_payload(self, token): + # the token is not active, does not exist on this server, or the + # protected resource is not allowed to introspect this particular + # token, then the authorization server MUST return an introspection + # response with the "active" field set to "false" + if not token: + return {'active': False} + if token.is_expired() or token.is_revoked(): + return {'active': False} + payload = self.introspect_token(token) + if 'active' not in payload: + payload['active'] = True + return payload + + def check_permission(self, token, client, request): + """Check if the request has permission to introspect the token. Developers + MUST implement this method:: + + def check_permission(self, token, client, request): + # only allow a special client to introspect the token + return client.client_id == 'introspection_client' + + :return: bool + """ + raise NotImplementedError() + + def query_token(self, token_string, token_type_hint): + """Get the token from database/storage by the given token string. + Developers should implement this method:: + + def query_token(self, token_string, token_type_hint): + if token_type_hint == 'access_token': + tok = Token.query_by_access_token(token_string) + elif token_type_hint == 'refresh_token': + tok = Token.query_by_refresh_token(token_string) + else: + tok = Token.query_by_access_token(token_string) + if not tok: + tok = Token.query_by_refresh_token(token_string) + return tok + """ + raise NotImplementedError() + + def introspect_token(self, token): + """Read given token and return its introspection metadata as a + dictionary following `Section 2.2`_:: + + def introspect_token(self, token): + return { + 'active': True, + 'client_id': token.client_id, + 'token_type': token.token_type, + 'username': get_token_username(token), + 'scope': token.get_scope(), + 'sub': get_token_user_sub(token), + 'aud': token.client_id, + 'iss': 'https://server.example.com/', + 'exp': token.expires_at, + 'iat': token.issued_at, + } + + .. _`Section 2.2`: https://tools.ietf.org/html/rfc7662#section-2.2 + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/models.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4f0c215bd762f02e4b3ed3fbbebbca830eb464 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/models.py @@ -0,0 +1,30 @@ +from ..rfc6749 import TokenMixin + + +class IntrospectionToken(dict, TokenMixin): + def get_client_id(self): + return self.get('client_id') + + def get_scope(self): + return self.get('scope') + + def get_expires_in(self): + # this method is only used in refresh token, + # no need to implement it + return 0 + + def get_expires_at(self): + return self.get('exp', 0) + + def __getattr__(self, key): + # https://tools.ietf.org/html/rfc7662#section-2.2 + available_keys = { + 'active', 'scope', 'client_id', 'username', 'token_type', + 'exp', 'iat', 'nbf', 'sub', 'aud', 'iss', 'jti' + } + try: + return object.__getattribute__(self, key) + except AttributeError as error: + if key in available_keys: + return self.get(key) + raise error diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/token_validator.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/token_validator.py new file mode 100644 index 0000000000000000000000000000000000000000..882c8d91cb937cb7ad4e4fc0ea74671a82bf2b02 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc7662/token_validator.py @@ -0,0 +1,34 @@ +from ..rfc6749 import TokenValidator +from ..rfc6750 import ( + InvalidTokenError, + InsufficientScopeError +) + + +class IntrospectTokenValidator(TokenValidator): + TOKEN_TYPE = 'bearer' + + def introspect_token(self, token_string): + """Request introspection token endpoint with the given token string, + authorization server will return token information in JSON format. + Developers MUST implement this method before using it:: + + def introspect_token(self, token_string): + # for example, introspection token endpoint has limited + # internal IPs to access, so there is no need to add + # authentication. + url = 'https://example.com/oauth/introspect' + resp = requests.post(url, data={'token': token_string}) + resp.raise_for_status() + return resp.json() + """ + raise NotImplementedError() + + def authenticate_token(self, token_string): + return self.introspect_token(token_string) + + def validate_token(self, token, scopes, request): + if not token or not token['active']: + raise InvalidTokenError(realm=self.realm, extra_attributes=self.extra_attributes) + if self.scope_insufficient(token.get('scope'), scopes): + raise InsufficientScopeError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8414/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8414/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b1b151c5d5a63bf04cfce74072fa4d0944e33d9d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8414/__init__.py @@ -0,0 +1,15 @@ +""" + authlib.oauth2.rfc8414 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents a direct implementation of + OAuth 2.0 Authorization Server Metadata. + + https://tools.ietf.org/html/rfc8414 +""" + +from .models import AuthorizationServerMetadata +from .well_known import get_well_known_url + + +__all__ = ['AuthorizationServerMetadata', 'get_well_known_url'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8414/models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8414/models.py new file mode 100644 index 0000000000000000000000000000000000000000..2dc790bddb442c2b8f9c57dd400abaafb5a769be --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8414/models.py @@ -0,0 +1,368 @@ +from authlib.common.urls import urlparse, is_valid_url +from authlib.common.security import is_secure_transport + + +class AuthorizationServerMetadata(dict): + """Define Authorization Server Metadata via `Section 2`_ in RFC8414_. + + .. _RFC8414: https://tools.ietf.org/html/rfc8414 + .. _`Section 2`: https://tools.ietf.org/html/rfc8414#section-2 + """ + REGISTRY_KEYS = [ + 'issuer', 'authorization_endpoint', 'token_endpoint', + 'jwks_uri', 'registration_endpoint', 'scopes_supported', + 'response_types_supported', 'response_modes_supported', + 'grant_types_supported', 'token_endpoint_auth_methods_supported', + 'token_endpoint_auth_signing_alg_values_supported', + 'service_documentation', 'ui_locales_supported', + 'op_policy_uri', 'op_tos_uri', 'revocation_endpoint', + 'revocation_endpoint_auth_methods_supported', + 'revocation_endpoint_auth_signing_alg_values_supported', + 'introspection_endpoint', + 'introspection_endpoint_auth_methods_supported', + 'introspection_endpoint_auth_signing_alg_values_supported', + 'code_challenge_methods_supported', + ] + + def validate_issuer(self): + """REQUIRED. The authorization server's issuer identifier, which is + a URL that uses the "https" scheme and has no query or fragment + components. + """ + issuer = self.get('issuer') + + #: 1. REQUIRED + if not issuer: + raise ValueError('"issuer" is required') + + parsed = urlparse.urlparse(issuer) + + #: 2. uses the "https" scheme + if not is_secure_transport(issuer): + raise ValueError('"issuer" MUST use "https" scheme') + + #: 3. has no query or fragment + if parsed.query or parsed.fragment: + raise ValueError('"issuer" has no query or fragment') + + def validate_authorization_endpoint(self): + """URL of the authorization server's authorization endpoint + [RFC6749]. This is REQUIRED unless no grant types are supported + that use the authorization endpoint. + """ + url = self.get('authorization_endpoint') + if url: + if not is_secure_transport(url): + raise ValueError( + '"authorization_endpoint" MUST use "https" scheme') + return + + grant_types_supported = set(self.grant_types_supported) + authorization_grant_types = {'authorization_code', 'implicit'} + if grant_types_supported & authorization_grant_types: + raise ValueError('"authorization_endpoint" is required') + + def validate_token_endpoint(self): + """URL of the authorization server's token endpoint [RFC6749]. This + is REQUIRED unless only the implicit grant type is supported. + """ + grant_types_supported = self.get('grant_types_supported') + if grant_types_supported and len(grant_types_supported) == 1 and \ + grant_types_supported[0] == 'implicit': + return + + url = self.get('token_endpoint') + if not url: + raise ValueError('"token_endpoint" is required') + + if not is_secure_transport(url): + raise ValueError('"token_endpoint" MUST use "https" scheme') + + def validate_jwks_uri(self): + """OPTIONAL. URL of the authorization server's JWK Set [JWK] + document. The referenced document contains the signing key(s) the + client uses to validate signatures from the authorization server. + This URL MUST use the "https" scheme. The JWK Set MAY also + contain the server's encryption key or keys, which are used by + clients to encrypt requests to the server. When both signing and + encryption keys are made available, a "use" (public key use) + parameter value is REQUIRED for all keys in the referenced JWK Set + to indicate each key's intended usage. + """ + url = self.get('jwks_uri') + if url and not is_secure_transport(url): + raise ValueError('"jwks_uri" MUST use "https" scheme') + + def validate_registration_endpoint(self): + """OPTIONAL. URL of the authorization server's OAuth 2.0 Dynamic + Client Registration endpoint [RFC7591]. + """ + url = self.get('registration_endpoint') + if url and not is_secure_transport(url): + raise ValueError( + '"registration_endpoint" MUST use "https" scheme') + + def validate_scopes_supported(self): + """RECOMMENDED. JSON array containing a list of the OAuth 2.0 + [RFC6749] "scope" values that this authorization server supports. + Servers MAY choose not to advertise some supported scope values + even when this parameter is used. + """ + validate_array_value(self, 'scopes_supported') + + def validate_response_types_supported(self): + """REQUIRED. JSON array containing a list of the OAuth 2.0 + "response_type" values that this authorization server supports. + The array values used are the same as those used with the + "response_types" parameter defined by "OAuth 2.0 Dynamic Client + Registration Protocol" [RFC7591]. + """ + response_types_supported = self.get('response_types_supported') + if not response_types_supported: + raise ValueError('"response_types_supported" is required') + if not isinstance(response_types_supported, list): + raise ValueError('"response_types_supported" MUST be JSON array') + + def validate_response_modes_supported(self): + """OPTIONAL. JSON array containing a list of the OAuth 2.0 + "response_mode" values that this authorization server supports, as + specified in "OAuth 2.0 Multiple Response Type Encoding Practices" + [OAuth.Responses]. If omitted, the default is "["query", + "fragment"]". The response mode value "form_post" is also defined + in "OAuth 2.0 Form Post Response Mode" [OAuth.Post]. + """ + validate_array_value(self, 'response_modes_supported') + + def validate_grant_types_supported(self): + """OPTIONAL. JSON array containing a list of the OAuth 2.0 grant + type values that this authorization server supports. The array + values used are the same as those used with the "grant_types" + parameter defined by "OAuth 2.0 Dynamic Client Registration + Protocol" [RFC7591]. If omitted, the default value is + "["authorization_code", "implicit"]". + """ + validate_array_value(self, 'grant_types_supported') + + def validate_token_endpoint_auth_methods_supported(self): + """OPTIONAL. JSON array containing a list of client authentication + methods supported by this token endpoint. Client authentication + method values are used in the "token_endpoint_auth_method" + parameter defined in Section 2 of [RFC7591]. If omitted, the + default is "client_secret_basic" -- the HTTP Basic Authentication + Scheme specified in Section 2.3.1 of OAuth 2.0 [RFC6749]. + """ + validate_array_value(self, 'token_endpoint_auth_methods_supported') + + def validate_token_endpoint_auth_signing_alg_values_supported(self): + """OPTIONAL. JSON array containing a list of the JWS signing + algorithms ("alg" values) supported by the token endpoint for the + signature on the JWT [JWT] used to authenticate the client at the + token endpoint for the "private_key_jwt" and "client_secret_jwt" + authentication methods. This metadata entry MUST be present if + either of these authentication methods are specified in the + "token_endpoint_auth_methods_supported" entry. No default + algorithms are implied if this entry is omitted. Servers SHOULD + support "RS256". The value "none" MUST NOT be used. + """ + _validate_alg_values( + self, + 'token_endpoint_auth_signing_alg_values_supported', + self.token_endpoint_auth_methods_supported + ) + + def validate_service_documentation(self): + """OPTIONAL. URL of a page containing human-readable information + that developers might want or need to know when using the + authorization server. In particular, if the authorization server + does not support Dynamic Client Registration, then information on + how to register clients needs to be provided in this + documentation. + """ + value = self.get('service_documentation') + if value and not is_valid_url(value): + raise ValueError('"service_documentation" MUST be a URL') + + def validate_ui_locales_supported(self): + """OPTIONAL. Languages and scripts supported for the user interface, + represented as a JSON array of language tag values from BCP 47 + [RFC5646]. If omitted, the set of supported languages and scripts + is unspecified. + """ + validate_array_value(self, 'ui_locales_supported') + + def validate_op_policy_uri(self): + """OPTIONAL. URL that the authorization server provides to the + person registering the client to read about the authorization + server's requirements on how the client can use the data provided + by the authorization server. The registration process SHOULD + display this URL to the person registering the client if it is + given. As described in Section 5, despite the identifier + "op_policy_uri" appearing to be OpenID-specific, its usage in this + specification is actually referring to a general OAuth 2.0 feature + that is not specific to OpenID Connect. + """ + value = self.get('op_policy_uri') + if value and not is_valid_url(value): + raise ValueError('"op_policy_uri" MUST be a URL') + + def validate_op_tos_uri(self): + """OPTIONAL. URL that the authorization server provides to the + person registering the client to read about the authorization + server's terms of service. The registration process SHOULD + display this URL to the person registering the client if it is + given. As described in Section 5, despite the identifier + "op_tos_uri", appearing to be OpenID-specific, its usage in this + specification is actually referring to a general OAuth 2.0 feature + that is not specific to OpenID Connect. + """ + value = self.get('op_tos_uri') + if value and not is_valid_url(value): + raise ValueError('"op_tos_uri" MUST be a URL') + + def validate_revocation_endpoint(self): + """OPTIONAL. URL of the authorization server's OAuth 2.0 revocation + endpoint [RFC7009].""" + url = self.get('revocation_endpoint') + if url and not is_secure_transport(url): + raise ValueError('"revocation_endpoint" MUST use "https" scheme') + + def validate_revocation_endpoint_auth_methods_supported(self): + """OPTIONAL. JSON array containing a list of client authentication + methods supported by this revocation endpoint. The valid client + authentication method values are those registered in the IANA + "OAuth Token Endpoint Authentication Methods" registry + [IANA.OAuth.Parameters]. If omitted, the default is + "client_secret_basic" -- the HTTP Basic Authentication Scheme + specified in Section 2.3.1 of OAuth 2.0 [RFC6749]. + """ + validate_array_value(self, 'revocation_endpoint_auth_methods_supported') + + def validate_revocation_endpoint_auth_signing_alg_values_supported(self): + """OPTIONAL. JSON array containing a list of the JWS signing + algorithms ("alg" values) supported by the revocation endpoint for + the signature on the JWT [JWT] used to authenticate the client at + the revocation endpoint for the "private_key_jwt" and + "client_secret_jwt" authentication methods. This metadata entry + MUST be present if either of these authentication methods are + specified in the "revocation_endpoint_auth_methods_supported" + entry. No default algorithms are implied if this entry is + omitted. The value "none" MUST NOT be used. + """ + _validate_alg_values( + self, + 'revocation_endpoint_auth_signing_alg_values_supported', + self.revocation_endpoint_auth_methods_supported + ) + + def validate_introspection_endpoint(self): + """OPTIONAL. URL of the authorization server's OAuth 2.0 + introspection endpoint [RFC7662]. + """ + url = self.get('introspection_endpoint') + if url and not is_secure_transport(url): + raise ValueError( + '"introspection_endpoint" MUST use "https" scheme') + + def validate_introspection_endpoint_auth_methods_supported(self): + """OPTIONAL. JSON array containing a list of client authentication + methods supported by this introspection endpoint. The valid + client authentication method values are those registered in the + IANA "OAuth Token Endpoint Authentication Methods" registry + [IANA.OAuth.Parameters] or those registered in the IANA "OAuth + Access Token Types" registry [IANA.OAuth.Parameters]. (These + values are and will remain distinct, due to Section 7.2.) If + omitted, the set of supported authentication methods MUST be + determined by other means. + """ + validate_array_value(self, 'introspection_endpoint_auth_methods_supported') + + def validate_introspection_endpoint_auth_signing_alg_values_supported(self): + """OPTIONAL. JSON array containing a list of the JWS signing + algorithms ("alg" values) supported by the introspection endpoint + for the signature on the JWT [JWT] used to authenticate the client + at the introspection endpoint for the "private_key_jwt" and + "client_secret_jwt" authentication methods. This metadata entry + MUST be present if either of these authentication methods are + specified in the "introspection_endpoint_auth_methods_supported" + entry. No default algorithms are implied if this entry is + omitted. The value "none" MUST NOT be used. + """ + _validate_alg_values( + self, + 'introspection_endpoint_auth_signing_alg_values_supported', + self.introspection_endpoint_auth_methods_supported + ) + + def validate_code_challenge_methods_supported(self): + """OPTIONAL. JSON array containing a list of Proof Key for Code + Exchange (PKCE) [RFC7636] code challenge methods supported by this + authorization server. Code challenge method values are used in + the "code_challenge_method" parameter defined in Section 4.3 of + [RFC7636]. The valid code challenge method values are those + registered in the IANA "PKCE Code Challenge Methods" registry + [IANA.OAuth.Parameters]. If omitted, the authorization server + does not support PKCE. + """ + validate_array_value(self, 'code_challenge_methods_supported') + + @property + def response_modes_supported(self): + #: If omitted, the default is ["query", "fragment"] + return self.get('response_modes_supported', ["query", "fragment"]) + + @property + def grant_types_supported(self): + #: If omitted, the default value is ["authorization_code", "implicit"] + return self.get('grant_types_supported', ["authorization_code", "implicit"]) + + @property + def token_endpoint_auth_methods_supported(self): + #: If omitted, the default is "client_secret_basic" + return self.get('token_endpoint_auth_methods_supported', ["client_secret_basic"]) + + @property + def revocation_endpoint_auth_methods_supported(self): + #: If omitted, the default is "client_secret_basic" + return self.get('revocation_endpoint_auth_methods_supported', ["client_secret_basic"]) + + @property + def introspection_endpoint_auth_methods_supported(self): + #: If omitted, the set of supported authentication methods MUST be + #: determined by other means + #: here, we use "client_secret_basic" + return self.get('introspection_endpoint_auth_methods_supported', ["client_secret_basic"]) + + def validate(self): + """Validate all server metadata value.""" + for key in self.REGISTRY_KEYS: + object.__getattribute__(self, f'validate_{key}')() + + def __getattr__(self, key): + try: + return object.__getattribute__(self, key) + except AttributeError as error: + if key in self.REGISTRY_KEYS: + return self.get(key) + raise error + + +def _validate_alg_values(data, key, auth_methods_supported): + value = data.get(key) + if value and not isinstance(value, list): + raise ValueError(f'"{key}" MUST be JSON array') + + auth_methods = set(auth_methods_supported) + jwt_auth_methods = {'private_key_jwt', 'client_secret_jwt'} + if auth_methods & jwt_auth_methods: + if not value: + raise ValueError(f'"{key}" is required') + + if value and 'none' in value: + raise ValueError( + f'the value "none" MUST NOT be used in "{key}"') + + +def validate_array_value(metadata, key): + values = metadata.get(key) + if values is not None and not isinstance(values, list): + raise ValueError(f'"{key}" MUST be JSON array') diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8414/well_known.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8414/well_known.py new file mode 100644 index 0000000000000000000000000000000000000000..42d70b3ba5316399d850f231928d8bb584fb6ca5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8414/well_known.py @@ -0,0 +1,22 @@ +from authlib.common.urls import urlparse + + +def get_well_known_url(issuer, external=False, suffix='oauth-authorization-server'): + """Get well-known URI with issuer via `Section 3.1`_. + + .. _`Section 3.1`: https://tools.ietf.org/html/rfc8414#section-3.1 + + :param issuer: URL of the issuer + :param external: return full external url or not + :param suffix: well-known URI suffix for RFC8414 + :return: URL + """ + parsed = urlparse.urlparse(issuer) + path = parsed.path + if path and path != '/': + url_path = f'/.well-known/{suffix}{path}' + else: + url_path = f'/.well-known/{suffix}' + if not external: + return url_path + return parsed.scheme + '://' + parsed.netloc + url_path diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6ad59fdfa915d0aef942c2740f2fc1dcf4a451f0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/__init__.py @@ -0,0 +1,22 @@ +""" + authlib.oauth2.rfc8628 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents an implementation of + OAuth 2.0 Device Authorization Grant. + + https://tools.ietf.org/html/rfc8628 +""" + +from .endpoint import DeviceAuthorizationEndpoint +from .device_code import DeviceCodeGrant, DEVICE_CODE_GRANT_TYPE +from .models import DeviceCredentialMixin, DeviceCredentialDict +from .errors import AuthorizationPendingError, SlowDownError, ExpiredTokenError + + +__all__ = [ + 'DeviceAuthorizationEndpoint', + 'DeviceCodeGrant', 'DEVICE_CODE_GRANT_TYPE', + 'DeviceCredentialMixin', 'DeviceCredentialDict', + 'AuthorizationPendingError', 'SlowDownError', 'ExpiredTokenError', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/device_code.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/device_code.py new file mode 100644 index 0000000000000000000000000000000000000000..682091705c05ebcce2dc2f42fa88444f189142c5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/device_code.py @@ -0,0 +1,183 @@ +import logging +from ..rfc6749.errors import ( + InvalidRequestError, + UnauthorizedClientError, + AccessDeniedError, +) +from ..rfc6749 import BaseGrant, TokenEndpointMixin +from .errors import ( + AuthorizationPendingError, + ExpiredTokenError, + SlowDownError, +) + +log = logging.getLogger(__name__) +DEVICE_CODE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code' + + +class DeviceCodeGrant(BaseGrant, TokenEndpointMixin): + """This OAuth 2.0 [RFC6749] protocol extension enables OAuth clients to + request user authorization from applications on devices that have + limited input capabilities or lack a suitable browser. Such devices + include smart TVs, media consoles, picture frames, and printers, + which lack an easy input method or a suitable browser required for + traditional OAuth interactions. Here is the authorization flow:: + + +----------+ +----------------+ + | |>---(A)-- Client Identifier --->| | + | | | | + | |<---(B)-- Device Code, ---<| | + | | User Code, | | + | Device | & Verification URI | | + | Client | | | + | | [polling] | | + | |>---(E)-- Device Code --->| | + | | & Client Identifier | | + | | | Authorization | + | |<---(F)-- Access Token ---<| Server | + +----------+ (& Optional Refresh Token) | | + v | | + : | | + (C) User Code & Verification URI | | + : | | + v | | + +----------+ | | + | End User | | | + | at |<---(D)-- End user reviews --->| | + | Browser | authorization request | | + +----------+ +----------------+ + + This DeviceCodeGrant is the implementation of step (E) and (F). + + (E) While the end user reviews the client's request (step D), the + client repeatedly polls the authorization server to find out if + the user completed the user authorization step. The client + includes the device code and its client identifier. + + (F) The authorization server validates the device code provided by + the client and responds with the access token if the client is + granted access, an error if they are denied access, or an + indication that the client should continue to poll. + """ + GRANT_TYPE = DEVICE_CODE_GRANT_TYPE + TOKEN_ENDPOINT_AUTH_METHODS = ['client_secret_basic', 'client_secret_post', 'none'] + + def validate_token_request(self): + """After displaying instructions to the user, the client creates an + access token request and sends it to the token endpoint with the + following parameters: + + grant_type + REQUIRED. Value MUST be set to + "urn:ietf:params:oauth:grant-type:device_code". + + device_code + REQUIRED. The device verification code, "device_code" from the + device authorization response. + + client_id + REQUIRED if the client is not authenticating with the + authorization server as described in Section 3.2.1. of [RFC6749]. + The client identifier as described in Section 2.2 of [RFC6749]. + + For example, the client makes the following HTTPS request:: + + POST /token HTTP/1.1 + Host: server.example.com + Content-Type: application/x-www-form-urlencoded + + grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code + &device_code=GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS + &client_id=1406020730 + """ + device_code = self.request.data.get('device_code') + if not device_code: + raise InvalidRequestError('Missing "device_code" in payload') + + client = self.authenticate_token_endpoint_client() + if not client.check_grant_type(self.GRANT_TYPE): + raise UnauthorizedClientError() + + credential = self.query_device_credential(device_code) + if not credential: + raise InvalidRequestError('Invalid "device_code" in payload') + + if credential.get_client_id() != client.get_client_id(): + raise UnauthorizedClientError() + + user = self.validate_device_credential(credential) + self.request.user = user + self.request.client = client + self.request.credential = credential + + def create_token_response(self): + """If the access token request is valid and authorized, the + authorization server issues an access token and optional refresh + token. + """ + client = self.request.client + scope = self.request.credential.get_scope() + token = self.generate_token( + user=self.request.user, + scope=scope, + include_refresh_token=client.check_grant_type('refresh_token'), + ) + log.debug('Issue token %r to %r', token, client) + self.save_token(token) + self.execute_hook('process_token', token=token) + return 200, token, self.TOKEN_RESPONSE_HEADER + + def validate_device_credential(self, credential): + if credential.is_expired(): + raise ExpiredTokenError() + + user_code = credential.get_user_code() + user_grant = self.query_user_grant(user_code) + + if user_grant is not None: + user, approved = user_grant + if not approved: + raise AccessDeniedError() + return user + + if self.should_slow_down(credential): + raise SlowDownError() + + raise AuthorizationPendingError() + + def query_device_credential(self, device_code): + """Get device credential from previously savings via ``DeviceAuthorizationEndpoint``. + Developers MUST implement it in subclass:: + + def query_device_credential(self, device_code): + return DeviceCredential.get(device_code) + + :param device_code: a string represent the code. + :return: DeviceCredential instance + """ + raise NotImplementedError() + + def query_user_grant(self, user_code): + """Get user and grant via the given user code. Developers MUST + implement it in subclass:: + + def query_user_grant(self, user_code): + # e.g. we saved user grant info in redis + data = redis.get('oauth_user_grant:' + user_code) + if not data: + return None + + user_id, allowed = data.split() + user = User.get(user_id) + return user, bool(allowed) + + Note, user grant information is saved by verification endpoint. + """ + raise NotImplementedError() + + def should_slow_down(self, credential): + """The authorization request is still pending and polling should + continue, but the interval MUST be increased by 5 seconds for this + and all subsequent requests. + """ + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/endpoint.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..49221f093153ee6fcab227495a7ed736a172bbbb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/endpoint.py @@ -0,0 +1,170 @@ +from authlib.consts import default_json_headers +from authlib.common.security import generate_token +from authlib.common.urls import add_params_to_uri + + +class DeviceAuthorizationEndpoint: + """This OAuth 2.0 [RFC6749] protocol extension enables OAuth clients to + request user authorization from applications on devices that have + limited input capabilities or lack a suitable browser. Such devices + include smart TVs, media consoles, picture frames, and printers, + which lack an easy input method or a suitable browser required for + traditional OAuth interactions. Here is the authorization flow:: + + +----------+ +----------------+ + | |>---(A)-- Client Identifier --->| | + | | | | + | |<---(B)-- Device Code, ---<| | + | | User Code, | | + | Device | & Verification URI | | + | Client | | | + | | [polling] | | + | |>---(E)-- Device Code --->| | + | | & Client Identifier | | + | | | Authorization | + | |<---(F)-- Access Token ---<| Server | + +----------+ (& Optional Refresh Token) | | + v | | + : | | + (C) User Code & Verification URI | | + : | | + v | | + +----------+ | | + | End User | | | + | at |<---(D)-- End user reviews --->| | + | Browser | authorization request | | + +----------+ +----------------+ + + This DeviceAuthorizationEndpoint is the implementation of step (A) and (B). + + (A) The client requests access from the authorization server and + includes its client identifier in the request. + + (B) The authorization server issues a device code and an end-user + code and provides the end-user verification URI. + """ + + ENDPOINT_NAME = 'device_authorization' + CLIENT_AUTH_METHODS = ['client_secret_basic', 'client_secret_post', 'none'] + + #: customize "user_code" type, string or digital + USER_CODE_TYPE = 'string' + + #: The lifetime in seconds of the "device_code" and "user_code" + EXPIRES_IN = 1800 + + #: The minimum amount of time in seconds that the client SHOULD + #: wait between polling requests to the token endpoint. + INTERVAL = 5 + + def __init__(self, server): + self.server = server + + def __call__(self, request): + # make it callable for authorization server + # ``create_endpoint_response`` + return self.create_endpoint_response(request) + + def create_endpoint_request(self, request): + return self.server.create_oauth2_request(request) + + def authenticate_client(self, request): + """client_id is REQUIRED **if the client is not** authenticating with the + authorization server as described in Section 3.2.1. of [RFC6749]. + + This means the endpoint support "none" authentication method. In this case, + this endpoint's auth methods are: + + - client_secret_basic + - client_secret_post + - none + + Developers change the value of ``CLIENT_AUTH_METHODS`` in subclass. For + instance:: + + class MyDeviceAuthorizationEndpoint(DeviceAuthorizationEndpoint): + # only support ``client_secret_basic`` auth method + CLIENT_AUTH_METHODS = ['client_secret_basic'] + """ + client = self.server.authenticate_client( + request, self.CLIENT_AUTH_METHODS, self.ENDPOINT_NAME) + request.client = client + return client + + def create_endpoint_response(self, request): + # https://tools.ietf.org/html/rfc8628#section-3.1 + + self.authenticate_client(request) + self.server.validate_requested_scope(request.scope) + + device_code = self.generate_device_code() + user_code = self.generate_user_code() + verification_uri = self.get_verification_uri() + verification_uri_complete = add_params_to_uri( + verification_uri, [('user_code', user_code)]) + + data = { + 'device_code': device_code, + 'user_code': user_code, + 'verification_uri': verification_uri, + 'verification_uri_complete': verification_uri_complete, + 'expires_in': self.EXPIRES_IN, + 'interval': self.INTERVAL, + } + + self.save_device_credential(request.client_id, request.scope, data) + return 200, data, default_json_headers + + def generate_user_code(self): + """A method to generate ``user_code`` value for device authorization + endpoint. This method will generate a random string like MQNA-JPOZ. + Developers can rewrite this method to create their own ``user_code``. + """ + # https://tools.ietf.org/html/rfc8628#section-6.1 + if self.USER_CODE_TYPE == 'digital': + return create_digital_user_code() + return create_string_user_code() + + def generate_device_code(self): + """A method to generate ``device_code`` value for device authorization + endpoint. This method will generate a random string of 42 characters. + Developers can rewrite this method to create their own ``device_code``. + """ + return generate_token(42) + + def get_verification_uri(self): + """Define the ``verification_uri`` of device authorization endpoint. + Developers MUST implement this method in subclass:: + + def get_verification_uri(self): + return 'https://your-company.com/active' + """ + raise NotImplementedError() + + def save_device_credential(self, client_id, scope, data): + """Save device token into database for later use. Developers MUST + implement this method in subclass:: + + def save_device_credential(self, client_id, scope, data): + item = DeviceCredential( + client_id=client_id, + scope=scope, + **data + ) + item.save() + """ + raise NotImplementedError() + + +def create_string_user_code(): + base = 'BCDFGHJKLMNPQRSTVWXZ' + return '-'.join([generate_token(4, base), generate_token(4, base)]) + + +def create_digital_user_code(): + base = '0123456789' + return '-'.join([ + generate_token(3, base), + generate_token(3, base), + generate_token(3, base), + ]) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/errors.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..4a63db8254dabf2c59c8d553a18565300e743580 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/errors.py @@ -0,0 +1,27 @@ +from ..rfc6749.errors import OAuth2Error + +# https://tools.ietf.org/html/rfc8628#section-3.5 + + +class AuthorizationPendingError(OAuth2Error): + """The authorization request is still pending as the end user hasn't + yet completed the user-interaction steps (Section 3.3). + """ + error = 'authorization_pending' + + +class SlowDownError(OAuth2Error): + """A variant of "authorization_pending", the authorization request is + still pending and polling should continue, but the interval MUST + be increased by 5 seconds for this and all subsequent requests. + """ + error = 'slow_down' + + +class ExpiredTokenError(OAuth2Error): + """The "device_code" has expired, and the device authorization + session has concluded. The client MAY commence a new device + authorization request but SHOULD wait for user interaction before + restarting to avoid unnecessary polling. + """ + error = 'expired_token' diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/models.py new file mode 100644 index 0000000000000000000000000000000000000000..39eb9a1388099975be3f70f4fc809eb5a209ce2f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8628/models.py @@ -0,0 +1,38 @@ +import time + + +class DeviceCredentialMixin: + def get_client_id(self): + raise NotImplementedError() + + def get_scope(self): + raise NotImplementedError() + + def get_user_code(self): + raise NotImplementedError() + + def is_expired(self): + raise NotImplementedError() + + +class DeviceCredentialDict(dict, DeviceCredentialMixin): + def get_client_id(self): + return self['client_id'] + + def get_scope(self): + return self.get('scope') + + def get_user_code(self): + return self['user_code'] + + def get_nonce(self): + return self.get('nonce') + + def get_auth_time(self): + return self.get('auth_time') + + def is_expired(self): + expires_at = self.get('expires_at') + if expires_at: + return expires_at < time.time() + return False diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8693/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8693/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1a74f856ec833c3f97661b5c2fe559b18ffd2556 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc8693/__init__.py @@ -0,0 +1,9 @@ +""" + authlib.oauth2.rfc8693 + ~~~~~~~~~~~~~~~~~~~~~~ + + This module represents an implementation of + OAuth 2.0 Token Exchange. + + https://tools.ietf.org/html/rfc8693 +""" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b914509a09461c97488150e704bb49d349a4ca2f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/__init__.py @@ -0,0 +1,11 @@ +from .introspection import JWTIntrospectionEndpoint +from .revocation import JWTRevocationEndpoint +from .token import JWTBearerTokenGenerator +from .token_validator import JWTBearerTokenValidator + +__all__ = [ + 'JWTBearerTokenGenerator', + 'JWTBearerTokenValidator', + 'JWTIntrospectionEndpoint', + 'JWTRevocationEndpoint', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/claims.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/claims.py new file mode 100644 index 0000000000000000000000000000000000000000..4dcfea8e1acea977a9daf76643ad10da09aab2f0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/claims.py @@ -0,0 +1,62 @@ +from authlib.jose.errors import InvalidClaimError +from authlib.jose.rfc7519 import JWTClaims + + +class JWTAccessTokenClaims(JWTClaims): + REGISTERED_CLAIMS = JWTClaims.REGISTERED_CLAIMS + [ + 'client_id', + 'auth_time', + 'acr', + 'amr', + 'scope', + 'groups', + 'roles', + 'entitlements', + ] + + def validate(self, **kwargs): + self.validate_typ() + + super().validate(**kwargs) + self.validate_client_id() + self.validate_auth_time() + self.validate_acr() + self.validate_amr() + self.validate_scope() + self.validate_groups() + self.validate_roles() + self.validate_entitlements() + + def validate_typ(self): + # The resource server MUST verify that the 'typ' header value is 'at+jwt' + # or 'application/at+jwt' and reject tokens carrying any other value. + if self.header['typ'].lower() not in ('at+jwt', 'application/at+jwt'): + raise InvalidClaimError('typ') + + def validate_client_id(self): + return self._validate_claim_value('client_id') + + def validate_auth_time(self): + auth_time = self.get('auth_time') + if auth_time and not isinstance(auth_time, (int, float)): + raise InvalidClaimError('auth_time') + + def validate_acr(self): + return self._validate_claim_value('acr') + + def validate_amr(self): + amr = self.get('amr') + if amr and not isinstance(self['amr'], list): + raise InvalidClaimError('amr') + + def validate_scope(self): + return self._validate_claim_value('scope') + + def validate_groups(self): + return self._validate_claim_value('groups') + + def validate_roles(self): + return self._validate_claim_value('roles') + + def validate_entitlements(self): + return self._validate_claim_value('entitlements') diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/introspection.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/introspection.py new file mode 100644 index 0000000000000000000000000000000000000000..17b5eb5a79f5b3d9b7df467742e806f7839b50a8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/introspection.py @@ -0,0 +1,126 @@ +from ..rfc7662 import IntrospectionEndpoint +from authlib.common.errors import ContinueIteration +from authlib.consts import default_json_headers +from authlib.jose.errors import ExpiredTokenError +from authlib.jose.errors import InvalidClaimError +from authlib.oauth2.rfc6750.errors import InvalidTokenError +from authlib.oauth2.rfc9068.token_validator import JWTBearerTokenValidator + + +class JWTIntrospectionEndpoint(IntrospectionEndpoint): + ''' + JWTIntrospectionEndpoint inherits from :ref:`specs/rfc7662` + :class:`~authlib.oauth2.rfc7662.IntrospectionEndpoint` and implements the machinery + to automatically process the JWT access tokens. + + :param issuer: The issuer identifier for which tokens will be introspected. + + :param \\*\\*kwargs: Other parameters are inherited from + :class:`~authlib.oauth2.rfc7662.introspection.IntrospectionEndpoint`. + + :: + + class MyJWTAccessTokenIntrospectionEndpoint(JWTRevocationEndpoint): + def get_jwks(self): + ... + + def get_username(self, user_id): + ... + + authorization_server.register_endpoint( + MyJWTAccessTokenIntrospectionEndpoint( + issuer="https://authorization-server.example.org", + ) + ) + authorization_server.register_endpoint(MyRefreshTokenIntrospectionEndpoint) + + ''' + + #: Endpoint name to be registered + ENDPOINT_NAME = 'introspection' + + def __init__(self, issuer, server=None, *args, **kwargs): + super().__init__(*args, server=server, **kwargs) + self.issuer = issuer + + def create_endpoint_response(self, request): + '''''' + # The authorization server first validates the client credentials + client = self.authenticate_endpoint_client(request) + + # then verifies whether the token was issued to the client making + # the revocation request + token = self.authenticate_token(request, client) + + # the authorization server invalidates the token + body = self.create_introspection_payload(token) + return 200, body, default_json_headers + + def authenticate_token(self, request, client): + '''''' + self.check_params(request, client) + + # do not attempt to decode refresh_tokens + if request.form.get('token_type_hint') not in ('access_token', None): + raise ContinueIteration() + + validator = JWTBearerTokenValidator(issuer=self.issuer, resource_server=None) + validator.get_jwks = self.get_jwks + try: + token = validator.authenticate_token(request.form['token']) + + # if the token is not a JWT, fall back to the regular flow + except InvalidTokenError: + raise ContinueIteration() + + if token and self.check_permission(token, client, request): + return token + + def create_introspection_payload(self, token): + if not token: + return {'active': False} + + try: + token.validate() + except ExpiredTokenError: + return {'active': False} + except InvalidClaimError as exc: + if exc.claim_name == 'iss': + raise ContinueIteration() + raise InvalidTokenError() + + + payload = { + 'active': True, + 'token_type': 'Bearer', + 'client_id': token['client_id'], + 'scope': token['scope'], + 'sub': token['sub'], + 'aud': token['aud'], + 'iss': token['iss'], + 'exp': token['exp'], + 'iat': token['iat'], + } + + if username := self.get_username(token['sub']): + payload['username'] = username + + return payload + + def get_jwks(self): + '''Return the JWKs that will be used to check the JWT access token signature. + Developers MUST re-implement this method:: + + def get_jwks(self): + return load_jwks("jwks.json") + ''' + raise NotImplementedError() + + def get_username(self, user_id: str) -> str: + '''Returns an username from a user ID. + Developers MAY re-implement this method:: + + def get_username(self, user_id): + return User.get(id=user_id).username + ''' + return None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/revocation.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/revocation.py new file mode 100644 index 0000000000000000000000000000000000000000..9453c79aec4e60c2358a8a68186d1fd0742067ac --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/revocation.py @@ -0,0 +1,70 @@ +from ..rfc6749 import UnsupportedTokenTypeError +from ..rfc7009 import RevocationEndpoint +from authlib.common.errors import ContinueIteration +from authlib.oauth2.rfc6750.errors import InvalidTokenError +from authlib.oauth2.rfc9068.token_validator import JWTBearerTokenValidator + + +class JWTRevocationEndpoint(RevocationEndpoint): + '''JWTRevocationEndpoint inherits from `RFC7009`_ + :class:`~authlib.oauth2.rfc7009.RevocationEndpoint`. + + The JWT access tokens cannot be revoked. + If the submitted token is a JWT access token, then revocation returns + a `invalid_token_error`. + + :param issuer: The issuer identifier. + + :param \\*\\*kwargs: Other parameters are inherited from + :class:`~authlib.oauth2.rfc7009.RevocationEndpoint`. + + Plain text access tokens and other kind of tokens such as refresh_tokens + will be ignored by this endpoint and passed to the next revocation endpoint:: + + class MyJWTAccessTokenRevocationEndpoint(JWTRevocationEndpoint): + def get_jwks(self): + ... + + authorization_server.register_endpoint( + MyJWTAccessTokenRevocationEndpoint( + issuer="https://authorization-server.example.org", + ) + ) + authorization_server.register_endpoint(MyRefreshTokenRevocationEndpoint) + + .. _RFC7009: https://tools.ietf.org/html/rfc7009 + ''' + + def __init__(self, issuer, server=None, *args, **kwargs): + super().__init__(*args, server=server, **kwargs) + self.issuer = issuer + + def authenticate_token(self, request, client): + '''''' + self.check_params(request, client) + + # do not attempt to revoke refresh_tokens + if request.form.get('token_type_hint') not in ('access_token', None): + raise ContinueIteration() + + validator = JWTBearerTokenValidator(issuer=self.issuer, resource_server=None) + validator.get_jwks = self.get_jwks + + try: + validator.authenticate_token(request.form['token']) + + # if the token is not a JWT, fall back to the regular flow + except InvalidTokenError: + raise ContinueIteration() + + # JWT access token cannot be revoked + raise UnsupportedTokenTypeError() + + def get_jwks(self): + '''Return the JWKs that will be used to check the JWT access token signature. + Developers MUST re-implement this method:: + + def get_jwks(self): + return load_jwks("jwks.json") + ''' + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/token.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/token.py new file mode 100644 index 0000000000000000000000000000000000000000..6751b88e9b5c65f7d8a224141c603a9742bb3dfb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/token.py @@ -0,0 +1,218 @@ +import time +from typing import List +from typing import Optional +from typing import Union + +from authlib.common.security import generate_token +from authlib.jose import jwt +from authlib.oauth2.rfc6750.token import BearerTokenGenerator + + +class JWTBearerTokenGenerator(BearerTokenGenerator): + '''A JWT formatted access token generator. + + :param issuer: The issuer identifier. Will appear in the JWT ``iss`` claim. + + :param \\*\\*kwargs: Other parameters are inherited from + :class:`~authlib.oauth2.rfc6750.token.BearerTokenGenerator`. + + This token generator can be registered into the authorization server:: + + class MyJWTBearerTokenGenerator(JWTBearerTokenGenerator): + def get_jwks(self): + ... + + def get_extra_claims(self, client, grant_type, user, scope): + ... + + authorization_server.register_token_generator( + 'default', + MyJWTBearerTokenGenerator(issuer='https://authorization-server.example.org'), + ) + ''' + + def __init__( + self, + issuer, + alg='RS256', + refresh_token_generator=None, + expires_generator=None, + ): + super().__init__( + self.access_token_generator, refresh_token_generator, expires_generator + ) + self.issuer = issuer + self.alg = alg + + def get_jwks(self): + '''Return the JWKs that will be used to sign the JWT access token. + Developers MUST re-implement this method:: + + def get_jwks(self): + return load_jwks("jwks.json") + ''' + raise NotImplementedError() + + def get_extra_claims(self, client, grant_type, user, scope): + '''Return extra claims to add in the JWT access token. Developers MAY + re-implement this method to add identity claims like the ones in + :ref:`specs/oidc` ID Token, or any other arbitrary claims:: + + def get_extra_claims(self, client, grant_type, user, scope): + return generate_user_info(user, scope) + ''' + return {} + + def get_audiences(self, client, user, scope) -> Union[str, List[str]]: + '''Return the audience for the token. By default this simply returns + the client ID. Developpers MAY re-implement this method to add extra + audiences:: + + def get_audiences(self, client, user, scope): + return [ + client.get_client_id(), + resource_server.get_id(), + ] + ''' + return client.get_client_id() + + def get_acr(self, user) -> Optional[str]: + '''Authentication Context Class Reference. + Returns a user-defined case sensitive string indicating the class of + authentication the used performed. Token audience may refuse to give access to + some resources if some ACR criterias are not met. + :ref:`specs/oidc` defines one special value: ``0`` means that the user + authentication did not respect `ISO29115`_ level 1, and will be refused monetary + operations. Developers MAY re-implement this method:: + + def get_acr(self, user): + if user.insecure_session(): + return '0' + return 'urn:mace:incommon:iap:silver' + + .. _ISO29115: https://www.iso.org/standard/45138.html + ''' + return None + + def get_auth_time(self, user) -> Optional[int]: + '''User authentication time. + Time when the End-User authentication occurred. Its value is a JSON number + representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC + until the date/time. Developers MAY re-implement this method:: + + def get_auth_time(self, user): + return datetime.timestamp(user.get_auth_time()) + ''' + return None + + def get_amr(self, user) -> Optional[List[str]]: + '''Authentication Methods References. + Defined by :ref:`specs/oidc` as an option list of user-defined case-sensitive + strings indication which authentication methods have been used to authenticate + the user. Developers MAY re-implement this method:: + + def get_amr(self, user): + return ['2FA'] if user.has_2fa_enabled() else [] + ''' + return None + + def get_jti(self, client, grant_type, user, scope) -> str: + '''JWT ID. + Create an unique identifier for the token. Developers MAY re-implement + this method:: + + def get_jti(self, client, grant_type, user scope): + return generate_random_string(16) + ''' + return generate_token(16) + + def access_token_generator(self, client, grant_type, user, scope): + now = int(time.time()) + expires_in = now + self._get_expires_in(client, grant_type) + + token_data = { + 'iss': self.issuer, + 'exp': expires_in, + 'client_id': client.get_client_id(), + 'iat': now, + 'jti': self.get_jti(client, grant_type, user, scope), + 'scope': scope, + } + + # In cases of access tokens obtained through grants where a resource owner is + # involved, such as the authorization code grant, the value of 'sub' SHOULD + # correspond to the subject identifier of the resource owner. + + if user: + token_data['sub'] = user.get_user_id() + + # In cases of access tokens obtained through grants where no resource owner is + # involved, such as the client credentials grant, the value of 'sub' SHOULD + # correspond to an identifier the authorization server uses to indicate the + # client application. + + else: + token_data['sub'] = client.get_client_id() + + # If the request includes a 'resource' parameter (as defined in [RFC8707]), the + # resulting JWT access token 'aud' claim SHOULD have the same value as the + # 'resource' parameter in the request. + + # TODO: Implement this with RFC8707 + if False: # pragma: no cover + ... + + # If the request does not include a 'resource' parameter, the authorization + # server MUST use a default resource indicator in the 'aud' claim. If a 'scope' + # parameter is present in the request, the authorization server SHOULD use it to + # infer the value of the default resource indicator to be used in the 'aud' + # claim. The mechanism through which scopes are associated with default resource + # indicator values is outside the scope of this specification. + + else: + token_data['aud'] = self.get_audiences(client, user, scope) + + # If the values in the 'scope' parameter refer to different default resource + # indicator values, the authorization server SHOULD reject the request with + # 'invalid_scope' as described in Section 4.1.2.1 of [RFC6749]. + # TODO: Implement this with RFC8707 + + if auth_time := self.get_auth_time(user): + token_data['auth_time'] = auth_time + + # The meaning and processing of acr Claim Values is out of scope for this + # specification. + + if acr := self.get_acr(user): + token_data['acr'] = acr + + # The definition of particular values to be used in the amr Claim is beyond the + # scope of this specification. + + if amr := self.get_amr(user): + token_data['amr'] = amr + + # Authorization servers MAY return arbitrary attributes not defined in any + # existing specification, as long as the corresponding claim names are collision + # resistant or the access tokens are meant to be used only within a private + # subsystem. Please refer to Sections 4.2 and 4.3 of [RFC7519] for details. + + token_data.update(self.get_extra_claims(client, grant_type, user, scope)) + + # This specification registers the 'application/at+jwt' media type, which can + # be used to indicate that the content is a JWT access token. JWT access tokens + # MUST include this media type in the 'typ' header parameter to explicitly + # declare that the JWT represents an access token complying with this profile. + # Per the definition of 'typ' in Section 4.1.9 of [RFC7515], it is RECOMMENDED + # that the 'application/' prefix be omitted. Therefore, the 'typ' value used + # SHOULD be 'at+jwt'. + + header = {'alg': self.alg, 'typ': 'at+jwt'} + + access_token = jwt.encode( + header, + token_data, + key=self.get_jwks(), + check=False, + ) + return access_token.decode() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/token_validator.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/token_validator.py new file mode 100644 index 0000000000000000000000000000000000000000..dc152e2898be68db9286599c7561f0fd1b76055c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oauth2/rfc9068/token_validator.py @@ -0,0 +1,163 @@ +''' + authlib.oauth2.rfc9068.token_validator + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Implementation of Validating JWT Access Tokens per `Section 4`_. + + .. _`Section 7`: https://www.rfc-editor.org/rfc/rfc9068.html#name-validating-jwt-access-token +''' +from authlib.jose import jwt +from authlib.jose.errors import DecodeError +from authlib.jose.errors import JoseError +from authlib.oauth2.rfc6750.errors import InsufficientScopeError +from authlib.oauth2.rfc6750.errors import InvalidTokenError +from authlib.oauth2.rfc6750.validator import BearerTokenValidator +from .claims import JWTAccessTokenClaims + + +class JWTBearerTokenValidator(BearerTokenValidator): + '''JWTBearerTokenValidator can protect your resource server endpoints. + + :param issuer: The issuer from which tokens will be accepted. + :param resource_server: An identifier for the current resource server, + which must appear in the JWT ``aud`` claim. + + Developers needs to implement the missing methods:: + + class MyJWTBearerTokenValidator(JWTBearerTokenValidator): + def get_jwks(self): + ... + + require_oauth = ResourceProtector() + require_oauth.register_token_validator( + MyJWTBearerTokenValidator( + issuer='https://authorization-server.example.org', + resource_server='https://resource-server.example.org', + ) + ) + + You can then protect resources depending on the JWT `scope`, `groups`, + `roles` or `entitlements` claims:: + + @require_oauth( + scope='profile', + groups='admins', + roles='student', + entitlements='captain', + ) + def resource_endpoint(): + ... + ''' + + def __init__(self, issuer, resource_server, *args, **kwargs): + self.issuer = issuer + self.resource_server = resource_server + super().__init__(*args, **kwargs) + + def get_jwks(self): + '''Return the JWKs that will be used to check the JWT access token signature. + Developers MUST re-implement this method. Typically the JWKs are statically + stored in the resource server configuration, or dynamically downloaded and + cached using :ref:`specs/rfc8414`:: + + def get_jwks(self): + if 'jwks' in cache: + return cache.get('jwks') + + server_metadata = get_server_metadata(self.issuer) + jwks_uri = server_metadata.get('jwks_uri') + cache['jwks'] = requests.get(jwks_uri).json() + return cache['jwks'] + ''' + raise NotImplementedError() + + def validate_iss(self, claims, iss: 'str') -> bool: + # The issuer identifier for the authorization server (which is typically + # obtained during discovery) MUST exactly match the value of the 'iss' + # claim. + return iss == self.issuer + + def authenticate_token(self, token_string): + '''''' + # empty docstring avoids to display the irrelevant parent docstring + + claims_options = { + 'iss': {'essential': True, 'validate': self.validate_iss}, + 'exp': {'essential': True}, + 'aud': {'essential': True, 'value': self.resource_server}, + 'sub': {'essential': True}, + 'client_id': {'essential': True}, + 'iat': {'essential': True}, + 'jti': {'essential': True}, + 'auth_time': {'essential': False}, + 'acr': {'essential': False}, + 'amr': {'essential': False}, + 'scope': {'essential': False}, + 'groups': {'essential': False}, + 'roles': {'essential': False}, + 'entitlements': {'essential': False}, + } + jwks = self.get_jwks() + + # If the JWT access token is encrypted, decrypt it using the keys and algorithms + # that the resource server specified during registration. If encryption was + # negotiated with the authorization server at registration time and the incoming + # JWT access token is not encrypted, the resource server SHOULD reject it. + + # The resource server MUST validate the signature of all incoming JWT access + # tokens according to [RFC7515] using the algorithm specified in the JWT 'alg' + # Header Parameter. The resource server MUST reject any JWT in which the value + # of 'alg' is 'none'. The resource server MUST use the keys provided by the + # authorization server. + try: + return jwt.decode( + token_string, + key=jwks, + claims_cls=JWTAccessTokenClaims, + claims_options=claims_options, + ) + except DecodeError: + raise InvalidTokenError( + realm=self.realm, extra_attributes=self.extra_attributes + ) + + def validate_token( + self, token, scopes, request, groups=None, roles=None, entitlements=None + ): + '''''' + # empty docstring avoids to display the irrelevant parent docstring + try: + token.validate() + except JoseError as exc: + raise InvalidTokenError( + realm=self.realm, extra_attributes=self.extra_attributes + ) from exc + + # If an authorization request includes a scope parameter, the corresponding + # issued JWT access token SHOULD include a 'scope' claim as defined in Section + # 4.2 of [RFC8693]. All the individual scope strings in the 'scope' claim MUST + # have meaning for the resources indicated in the 'aud' claim. See Section 5 for + # more considerations about the relationship between scope strings and resources + # indicated by the 'aud' claim. + + if self.scope_insufficient(token.get('scope', []), scopes): + raise InsufficientScopeError() + + # Many authorization servers embed authorization attributes that go beyond the + # delegated scenarios described by [RFC7519] in the access tokens they issue. + # Typical examples include resource owner memberships in roles and groups that + # are relevant to the resource being accessed, entitlements assigned to the + # resource owner for the targeted resource that the authorization server knows + # about, and so on. An authorization server wanting to include such attributes + # in a JWT access token SHOULD use the 'groups', 'roles', and 'entitlements' + # attributes of the 'User' resource schema defined by Section 4.1.2 of + # [RFC7643]) as claim types. + + if self.scope_insufficient(token.get('groups'), groups): + raise InvalidTokenError() + + if self.scope_insufficient(token.get('roles'), roles): + raise InvalidTokenError() + + if self.scope_insufficient(token.get('entitlements'), entitlements): + raise InvalidTokenError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..212ebc031322a8079d2801b905c424145e5fbd5b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/__init__.py @@ -0,0 +1,23 @@ +""" + authlib.oidc.core + ~~~~~~~~~~~~~~~~~ + + OpenID Connect Core 1.0 Implementation. + + http://openid.net/specs/openid-connect-core-1_0.html +""" + +from .models import AuthorizationCodeMixin +from .claims import ( + IDToken, CodeIDToken, ImplicitIDToken, HybridIDToken, + UserInfo, get_claim_cls_by_response_type, +) +from .grants import OpenIDToken, OpenIDCode, OpenIDHybridGrant, OpenIDImplicitGrant + + +__all__ = [ + 'AuthorizationCodeMixin', + 'IDToken', 'CodeIDToken', 'ImplicitIDToken', 'HybridIDToken', + 'UserInfo', 'get_claim_cls_by_response_type', + 'OpenIDToken', 'OpenIDCode', 'OpenIDHybridGrant', 'OpenIDImplicitGrant', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/claims.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/claims.py new file mode 100644 index 0000000000000000000000000000000000000000..f867458554ca0f21e7293cf7e5abaf9bc8e46939 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/claims.py @@ -0,0 +1,242 @@ +import time +import hmac +from authlib.common.encoding import to_bytes +from authlib.jose import JWTClaims +from authlib.jose.errors import ( + MissingClaimError, + InvalidClaimError, +) +from .util import create_half_hash + +__all__ = [ + 'IDToken', 'CodeIDToken', 'ImplicitIDToken', 'HybridIDToken', + 'UserInfo', 'get_claim_cls_by_response_type' +] + +_REGISTERED_CLAIMS = [ + 'iss', 'sub', 'aud', 'exp', 'nbf', 'iat', + 'auth_time', 'nonce', 'acr', 'amr', 'azp', + 'at_hash', +] + + +class IDToken(JWTClaims): + ESSENTIAL_CLAIMS = ['iss', 'sub', 'aud', 'exp', 'iat'] + + def validate(self, now=None, leeway=0): + for k in self.ESSENTIAL_CLAIMS: + if k not in self: + raise MissingClaimError(k) + + self._validate_essential_claims() + if now is None: + now = int(time.time()) + + self.validate_iss() + self.validate_sub() + self.validate_aud() + self.validate_exp(now, leeway) + self.validate_nbf(now, leeway) + self.validate_iat(now, leeway) + self.validate_auth_time() + self.validate_nonce() + self.validate_acr() + self.validate_amr() + self.validate_azp() + self.validate_at_hash() + + def validate_auth_time(self): + """Time when the End-User authentication occurred. Its value is a JSON + number representing the number of seconds from 1970-01-01T0:0:0Z as + measured in UTC until the date/time. When a max_age request is made or + when auth_time is requested as an Essential Claim, then this Claim is + REQUIRED; otherwise, its inclusion is OPTIONAL. + """ + auth_time = self.get('auth_time') + if self.params.get('max_age') and not auth_time: + raise MissingClaimError('auth_time') + + if auth_time and not isinstance(auth_time, (int, float)): + raise InvalidClaimError('auth_time') + + def validate_nonce(self): + """String value used to associate a Client session with an ID Token, + and to mitigate replay attacks. The value is passed through unmodified + from the Authentication Request to the ID Token. If present in the ID + Token, Clients MUST verify that the nonce Claim Value is equal to the + value of the nonce parameter sent in the Authentication Request. If + present in the Authentication Request, Authorization Servers MUST + include a nonce Claim in the ID Token with the Claim Value being the + nonce value sent in the Authentication Request. Authorization Servers + SHOULD perform no other processing on nonce values used. The nonce + value is a case sensitive string. + """ + nonce_value = self.params.get('nonce') + if nonce_value: + if 'nonce' not in self: + raise MissingClaimError('nonce') + if nonce_value != self['nonce']: + raise InvalidClaimError('nonce') + + def validate_acr(self): + """OPTIONAL. Authentication Context Class Reference. String specifying + an Authentication Context Class Reference value that identifies the + Authentication Context Class that the authentication performed + satisfied. The value "0" indicates the End-User authentication did not + meet the requirements of `ISO/IEC 29115`_ level 1. Authentication + using a long-lived browser cookie, for instance, is one example where + the use of "level 0" is appropriate. Authentications with level 0 + SHOULD NOT be used to authorize access to any resource of any monetary + value. An absolute URI or an `RFC 6711`_ registered name SHOULD be + used as the acr value; registered names MUST NOT be used with a + different meaning than that which is registered. Parties using this + claim will need to agree upon the meanings of the values used, which + may be context-specific. The acr value is a case sensitive string. + + .. _`ISO/IEC 29115`: https://www.iso.org/standard/45138.html + .. _`RFC 6711`: https://tools.ietf.org/html/rfc6711 + """ + return self._validate_claim_value('acr') + + def validate_amr(self): + """OPTIONAL. Authentication Methods References. JSON array of strings + that are identifiers for authentication methods used in the + authentication. For instance, values might indicate that both password + and OTP authentication methods were used. The definition of particular + values to be used in the amr Claim is beyond the scope of this + specification. Parties using this claim will need to agree upon the + meanings of the values used, which may be context-specific. The amr + value is an array of case sensitive strings. + """ + amr = self.get('amr') + if amr and not isinstance(self['amr'], list): + raise InvalidClaimError('amr') + + def validate_azp(self): + """OPTIONAL. Authorized party - the party to which the ID Token was + issued. If present, it MUST contain the OAuth 2.0 Client ID of this + party. This Claim is only needed when the ID Token has a single + audience value and that audience is different than the authorized + party. It MAY be included even when the authorized party is the same + as the sole audience. The azp value is a case sensitive string + containing a StringOrURI value. + """ + aud = self.get('aud') + client_id = self.params.get('client_id') + required = False + if aud and client_id: + if isinstance(aud, list) and len(aud) == 1: + aud = aud[0] + if aud != client_id: + required = True + + azp = self.get('azp') + if required and not azp: + raise MissingClaimError('azp') + + if azp and client_id and azp != client_id: + raise InvalidClaimError('azp') + + def validate_at_hash(self): + """OPTIONAL. Access Token hash value. Its value is the base64url + encoding of the left-most half of the hash of the octets of the ASCII + representation of the access_token value, where the hash algorithm + used is the hash algorithm used in the alg Header Parameter of the + ID Token's JOSE Header. For instance, if the alg is RS256, hash the + access_token value with SHA-256, then take the left-most 128 bits and + base64url encode them. The at_hash value is a case sensitive string. + """ + access_token = self.params.get('access_token') + at_hash = self.get('at_hash') + if at_hash and access_token: + if not _verify_hash(at_hash, access_token, self.header['alg']): + raise InvalidClaimError('at_hash') + + +class CodeIDToken(IDToken): + RESPONSE_TYPES = ('code',) + REGISTERED_CLAIMS = _REGISTERED_CLAIMS + + +class ImplicitIDToken(IDToken): + RESPONSE_TYPES = ('id_token', 'id_token token') + ESSENTIAL_CLAIMS = ['iss', 'sub', 'aud', 'exp', 'iat', 'nonce'] + REGISTERED_CLAIMS = _REGISTERED_CLAIMS + + def validate_at_hash(self): + """If the ID Token is issued from the Authorization Endpoint with an + access_token value, which is the case for the response_type value + id_token token, this is REQUIRED; it MAY NOT be used when no Access + Token is issued, which is the case for the response_type value + id_token. + """ + access_token = self.params.get('access_token') + if access_token and 'at_hash' not in self: + raise MissingClaimError('at_hash') + super().validate_at_hash() + + +class HybridIDToken(ImplicitIDToken): + RESPONSE_TYPES = ('code id_token', 'code token', 'code id_token token') + REGISTERED_CLAIMS = _REGISTERED_CLAIMS + ['c_hash'] + + def validate(self, now=None, leeway=0): + super().validate(now=now, leeway=leeway) + self.validate_c_hash() + + def validate_c_hash(self): + """Code hash value. Its value is the base64url encoding of the + left-most half of the hash of the octets of the ASCII representation + of the code value, where the hash algorithm used is the hash algorithm + used in the alg Header Parameter of the ID Token's JOSE Header. For + instance, if the alg is HS512, hash the code value with SHA-512, then + take the left-most 256 bits and base64url encode them. The c_hash + value is a case sensitive string. + If the ID Token is issued from the Authorization Endpoint with a code, + which is the case for the response_type values code id_token and code + id_token token, this is REQUIRED; otherwise, its inclusion is OPTIONAL. + """ + code = self.params.get('code') + c_hash = self.get('c_hash') + if code: + if not c_hash: + raise MissingClaimError('c_hash') + if not _verify_hash(c_hash, code, self.header['alg']): + raise InvalidClaimError('c_hash') + + +class UserInfo(dict): + """The standard claims of a UserInfo object. Defined per `Section 5.1`_. + + .. _`Section 5.1`: http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims + """ + + #: registered claims that UserInfo supports + REGISTERED_CLAIMS = [ + 'sub', 'name', 'given_name', 'family_name', 'middle_name', 'nickname', + 'preferred_username', 'profile', 'picture', 'website', 'email', + 'email_verified', 'gender', 'birthdate', 'zoneinfo', 'locale', + 'phone_number', 'phone_number_verified', 'address', 'updated_at', + ] + + def __getattr__(self, key): + try: + return object.__getattribute__(self, key) + except AttributeError as error: + if key in self.REGISTERED_CLAIMS: + return self.get(key) + raise error + + +def get_claim_cls_by_response_type(response_type): + claims_classes = (CodeIDToken, ImplicitIDToken, HybridIDToken) + for claims_cls in claims_classes: + if response_type in claims_cls.RESPONSE_TYPES: + return claims_cls + + +def _verify_hash(signature, s, alg): + hash_value = create_half_hash(s, alg) + if not hash_value: + return True + return hmac.compare_digest(hash_value, to_bytes(signature)) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/errors.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..e5fb630e39e381c8ba6ed40be84f279f78c45637 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/errors.py @@ -0,0 +1,78 @@ +from authlib.oauth2 import OAuth2Error + + +class InteractionRequiredError(OAuth2Error): + """The Authorization Server requires End-User interaction of some form + to proceed. This error MAY be returned when the prompt parameter value + in the Authentication Request is none, but the Authentication Request + cannot be completed without displaying a user interface for End-User + interaction. + + http://openid.net/specs/openid-connect-core-1_0.html#AuthError + """ + error = 'interaction_required' + + +class LoginRequiredError(OAuth2Error): + """The Authorization Server requires End-User authentication. This error + MAY be returned when the prompt parameter value in the Authentication + Request is none, but the Authentication Request cannot be completed + without displaying a user interface for End-User authentication. + + http://openid.net/specs/openid-connect-core-1_0.html#AuthError + """ + error = 'login_required' + + +class AccountSelectionRequiredError(OAuth2Error): + """The End-User is REQUIRED to select a session at the Authorization + Server. The End-User MAY be authenticated at the Authorization Server + with different associated accounts, but the End-User did not select a + session. This error MAY be returned when the prompt parameter value in + the Authentication Request is none, but the Authentication Request cannot + be completed without displaying a user interface to prompt for a session + to use. + + http://openid.net/specs/openid-connect-core-1_0.html#AuthError + """ + error = 'account_selection_required' + + +class ConsentRequiredError(OAuth2Error): + """The Authorization Server requires End-User consent. This error MAY be + returned when the prompt parameter value in the Authentication Request is + none, but the Authentication Request cannot be completed without + displaying a user interface for End-User consent. + + http://openid.net/specs/openid-connect-core-1_0.html#AuthError + """ + error = 'consent_required' + + +class InvalidRequestURIError(OAuth2Error): + """The request_uri in the Authorization Request returns an error or + contains invalid data. + + http://openid.net/specs/openid-connect-core-1_0.html#AuthError + """ + error = 'invalid_request_uri' + + +class InvalidRequestObjectError(OAuth2Error): + """The request parameter contains an invalid Request Object.""" + error = 'invalid_request_object' + + +class RequestNotSupportedError(OAuth2Error): + """The OP does not support use of the request parameter.""" + error = 'request_not_supported' + + +class RequestURINotSupportedError(OAuth2Error): + """The OP does not support use of the request_uri parameter.""" + error = 'request_uri_not_supported' + + +class RegistrationNotSupportedError(OAuth2Error): + """The OP does not support use of the registration parameter.""" + error = 'registration_not_supported' diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b4b00252a7d99ee11bcaa799795a629ee7f7d08 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/__init__.py @@ -0,0 +1,10 @@ +from .code import OpenIDToken, OpenIDCode +from .implicit import OpenIDImplicitGrant +from .hybrid import OpenIDHybridGrant + +__all__ = [ + 'OpenIDToken', + 'OpenIDCode', + 'OpenIDImplicitGrant', + 'OpenIDHybridGrant', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/code.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/code.py new file mode 100644 index 0000000000000000000000000000000000000000..9ac3bfbb494387f8df10d9b0798080b525872fb4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/code.py @@ -0,0 +1,142 @@ +""" + authlib.oidc.core.grants.code + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Implementation of Authentication using the Authorization Code Flow + per `Section 3.1`_. + + .. _`Section 3.1`: http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth +""" + +import logging +from authlib.oauth2.rfc6749 import OAuth2Request +from .util import ( + is_openid_scope, + validate_nonce, + validate_request_prompt, + generate_id_token, +) + +log = logging.getLogger(__name__) + + +class OpenIDToken: + def get_jwt_config(self, grant): # pragma: no cover + """Get the JWT configuration for OpenIDCode extension. The JWT + configuration will be used to generate ``id_token``. Developers + MUST implement this method in subclass, e.g.:: + + def get_jwt_config(self, grant): + return { + 'key': read_private_key_file(key_path), + 'alg': 'RS256', + 'iss': 'issuer-identity', + 'exp': 3600 + } + + :param grant: AuthorizationCodeGrant instance + :return: dict + """ + raise NotImplementedError() + + def generate_user_info(self, user, scope): + """Provide user information for the given scope. Developers + MUST implement this method in subclass, e.g.:: + + from authlib.oidc.core import UserInfo + + def generate_user_info(self, user, scope): + user_info = UserInfo(sub=user.id, name=user.name) + if 'email' in scope: + user_info['email'] = user.email + return user_info + + :param user: user instance + :param scope: scope of the token + :return: ``authlib.oidc.core.UserInfo`` instance + """ + raise NotImplementedError() + + def get_audiences(self, request): + """Parse `aud` value for id_token, default value is client id. Developers + MAY rewrite this method to provide a customized audience value. + """ + client = request.client + return [client.get_client_id()] + + def process_token(self, grant, token): + scope = token.get('scope') + if not scope or not is_openid_scope(scope): + # standard authorization code flow + return token + + request: OAuth2Request = grant.request + authorization_code = request.authorization_code + + config = self.get_jwt_config(grant) + config['aud'] = self.get_audiences(request) + + if authorization_code: + config['nonce'] = authorization_code.get_nonce() + config['auth_time'] = authorization_code.get_auth_time() + + user_info = self.generate_user_info(request.user, token['scope']) + id_token = generate_id_token(token, user_info, **config) + token['id_token'] = id_token + return token + + def __call__(self, grant): + grant.register_hook('process_token', self.process_token) + + +class OpenIDCode(OpenIDToken): + """An extension from OpenID Connect for "grant_type=code" request. Developers + MUST implement the missing methods:: + + class MyOpenIDCode(OpenIDCode): + def get_jwt_config(self, grant): + return {...} + + def exists_nonce(self, nonce, request): + return check_if_nonce_in_cache(request.client_id, nonce) + + def generate_user_info(self, user, scope): + return {...} + + The register this extension with AuthorizationCodeGrant:: + + authorization_server.register_grant(AuthorizationCodeGrant, extensions=[MyOpenIDCode()]) + """ + def __init__(self, require_nonce=False): + self.require_nonce = require_nonce + + def exists_nonce(self, nonce, request): + """Check if the given nonce is existing in your database. Developers + MUST implement this method in subclass, e.g.:: + + def exists_nonce(self, nonce, request): + exists = AuthorizationCode.query.filter_by( + client_id=request.client_id, nonce=nonce + ).first() + return bool(exists) + + :param nonce: A string of "nonce" parameter in request + :param request: OAuth2Request instance + :return: Boolean + """ + raise NotImplementedError() + + def validate_openid_authorization_request(self, grant): + validate_nonce(grant.request, self.exists_nonce, self.require_nonce) + + def __call__(self, grant): + grant.register_hook('process_token', self.process_token) + if is_openid_scope(grant.request.scope): + grant.register_hook( + 'after_validate_authorization_request', + self.validate_openid_authorization_request + ) + grant.register_hook( + 'after_validate_consent_request', + validate_request_prompt + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/hybrid.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/hybrid.py new file mode 100644 index 0000000000000000000000000000000000000000..384c86730635d21bf9d766b00d05650819b1127a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/hybrid.py @@ -0,0 +1,90 @@ +import logging +from authlib.common.security import generate_token +from authlib.oauth2.rfc6749 import InvalidScopeError +from authlib.oauth2.rfc6749.grants.authorization_code import ( + validate_code_authorization_request +) +from .implicit import OpenIDImplicitGrant +from .util import is_openid_scope, validate_nonce + +log = logging.getLogger(__name__) + + +class OpenIDHybridGrant(OpenIDImplicitGrant): + #: Generated "code" length + AUTHORIZATION_CODE_LENGTH = 48 + + RESPONSE_TYPES = {'code id_token', 'code token', 'code id_token token'} + GRANT_TYPE = 'code' + DEFAULT_RESPONSE_MODE = 'fragment' + + def generate_authorization_code(self): + """"The method to generate "code" value for authorization code data. + Developers may rewrite this method, or customize the code length with:: + + class MyAuthorizationCodeGrant(AuthorizationCodeGrant): + AUTHORIZATION_CODE_LENGTH = 32 # default is 48 + """ + return generate_token(self.AUTHORIZATION_CODE_LENGTH) + + def save_authorization_code(self, code, request): + """Save authorization_code for later use. Developers MUST implement + it in subclass. Here is an example:: + + def save_authorization_code(self, code, request): + client = request.client + auth_code = AuthorizationCode( + code=code, + client_id=client.client_id, + redirect_uri=request.redirect_uri, + scope=request.scope, + nonce=request.data.get('nonce'), + user_id=request.user.id, + ) + auth_code.save() + """ + raise NotImplementedError() + + def validate_authorization_request(self): + if not is_openid_scope(self.request.scope): + raise InvalidScopeError( + 'Missing "openid" scope', + redirect_uri=self.request.redirect_uri, + redirect_fragment=True, + ) + self.register_hook( + 'after_validate_authorization_request', + lambda grant: validate_nonce( + grant.request, grant.exists_nonce, required=True) + ) + return validate_code_authorization_request(self) + + def create_granted_params(self, grant_user): + self.request.user = grant_user + client = self.request.client + code = self.generate_authorization_code() + self.save_authorization_code(code, self.request) + params = [('code', code)] + token = self.generate_token( + grant_type='implicit', + user=grant_user, + scope=self.request.scope, + include_refresh_token=False + ) + + response_types = self.request.response_type.split() + if 'token' in response_types: + log.debug('Grant token %r to %r', token, client) + self.server.save_token(token, self.request) + if 'id_token' in response_types: + token = self.process_implicit_token(token, code) + else: + # response_type is "code id_token" + token = { + 'expires_in': token['expires_in'], + 'scope': token['scope'] + } + token = self.process_implicit_token(token, code) + + params.extend([(k, token[k]) for k in token]) + return params diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/implicit.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/implicit.py new file mode 100644 index 0000000000000000000000000000000000000000..15bc1facea5f1320be5a243608d2677a6c6f8b71 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/implicit.py @@ -0,0 +1,150 @@ +import logging +from authlib.oauth2.rfc6749 import ( + OAuth2Error, + InvalidScopeError, + AccessDeniedError, + ImplicitGrant, +) +from .util import ( + is_openid_scope, + validate_nonce, + validate_request_prompt, + create_response_mode_response, + generate_id_token, +) + +log = logging.getLogger(__name__) + + +class OpenIDImplicitGrant(ImplicitGrant): + RESPONSE_TYPES = {'id_token token', 'id_token'} + DEFAULT_RESPONSE_MODE = 'fragment' + + def exists_nonce(self, nonce, request): + """Check if the given nonce is existing in your database. Developers + should implement this method in subclass, e.g.:: + + def exists_nonce(self, nonce, request): + exists = AuthorizationCode.query.filter_by( + client_id=request.client_id, nonce=nonce + ).first() + return bool(exists) + + :param nonce: A string of "nonce" parameter in request + :param request: OAuth2Request instance + :return: Boolean + """ + raise NotImplementedError() + + def get_jwt_config(self): + """Get the JWT configuration for OpenIDImplicitGrant. The JWT + configuration will be used to generate ``id_token``. Developers + MUST implement this method in subclass, e.g.:: + + def get_jwt_config(self): + return { + 'key': read_private_key_file(key_path), + 'alg': 'RS256', + 'iss': 'issuer-identity', + 'exp': 3600 + } + + :return: dict + """ + raise NotImplementedError() + + def generate_user_info(self, user, scope): + """Provide user information for the given scope. Developers + MUST implement this method in subclass, e.g.:: + + from authlib.oidc.core import UserInfo + + def generate_user_info(self, user, scope): + user_info = UserInfo(sub=user.id, name=user.name) + if 'email' in scope: + user_info['email'] = user.email + return user_info + + :param user: user instance + :param scope: scope of the token + :return: ``authlib.oidc.core.UserInfo`` instance + """ + raise NotImplementedError() + + def get_audiences(self, request): + """Parse `aud` value for id_token, default value is client id. Developers + MAY rewrite this method to provide a customized audience value. + """ + client = request.client + return [client.get_client_id()] + + def validate_authorization_request(self): + if not is_openid_scope(self.request.scope): + raise InvalidScopeError( + 'Missing "openid" scope', + redirect_uri=self.request.redirect_uri, + redirect_fragment=True, + ) + redirect_uri = super().validate_authorization_request() + try: + validate_nonce(self.request, self.exists_nonce, required=True) + except OAuth2Error as error: + error.redirect_uri = redirect_uri + error.redirect_fragment = True + raise error + return redirect_uri + + def validate_consent_request(self): + redirect_uri = self.validate_authorization_request() + validate_request_prompt(self, redirect_uri, redirect_fragment=True) + + def create_authorization_response(self, redirect_uri, grant_user): + state = self.request.state + if grant_user: + params = self.create_granted_params(grant_user) + if state: + params.append(('state', state)) + else: + error = AccessDeniedError(state=state) + params = error.get_body() + + # http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes + response_mode = self.request.data.get('response_mode', self.DEFAULT_RESPONSE_MODE) + return create_response_mode_response( + redirect_uri=redirect_uri, + params=params, + response_mode=response_mode, + ) + + def create_granted_params(self, grant_user): + self.request.user = grant_user + client = self.request.client + token = self.generate_token( + user=grant_user, + scope=self.request.scope, + include_refresh_token=False + ) + if self.request.response_type == 'id_token': + token = { + 'expires_in': token['expires_in'], + 'scope': token['scope'], + } + token = self.process_implicit_token(token) + else: + log.debug('Grant token %r to %r', token, client) + self.server.save_token(token, self.request) + token = self.process_implicit_token(token) + params = [(k, token[k]) for k in token] + return params + + def process_implicit_token(self, token, code=None): + config = self.get_jwt_config() + config['aud'] = self.get_audiences(self.request) + config['nonce'] = self.request.data.get('nonce') + if code is not None: + config['code'] = code + + user_info = self.generate_user_info(self.request.user, token['scope']) + id_token = generate_id_token(token, user_info, **config) + token['id_token'] = id_token + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/util.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/util.py new file mode 100644 index 0000000000000000000000000000000000000000..3b57dbe88d11c43ad0b1b5dd2a51baf49e3eee9f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/grants/util.py @@ -0,0 +1,131 @@ +import time +from authlib.oauth2.rfc6749 import InvalidRequestError +from authlib.oauth2.rfc6749 import scope_to_list +from authlib.jose import jwt +from authlib.common.encoding import to_native +from authlib.common.urls import add_params_to_uri, quote_url +from ..util import create_half_hash +from ..errors import ( + LoginRequiredError, + AccountSelectionRequiredError, + ConsentRequiredError, +) + + +def is_openid_scope(scope): + scopes = scope_to_list(scope) + return scopes and 'openid' in scopes + + +def validate_request_prompt(grant, redirect_uri, redirect_fragment=False): + prompt = grant.request.data.get('prompt') + end_user = grant.request.user + if not prompt: + if not end_user: + grant.prompt = 'login' + return grant + + if prompt == 'none' and not end_user: + raise LoginRequiredError( + redirect_uri=redirect_uri, + redirect_fragment=redirect_fragment) + + prompts = prompt.split() + if 'none' in prompts and len(prompts) > 1: + # If this parameter contains none with any other value, + # an error is returned + raise InvalidRequestError( + 'Invalid "prompt" parameter.', + redirect_uri=redirect_uri, + redirect_fragment=redirect_fragment) + + prompt = _guess_prompt_value( + end_user, prompts, redirect_uri, redirect_fragment=redirect_fragment) + if prompt: + grant.prompt = prompt + return grant + + +def validate_nonce(request, exists_nonce, required=False): + nonce = request.data.get('nonce') + if not nonce: + if required: + raise InvalidRequestError('Missing "nonce" in request.') + return True + + if exists_nonce(nonce, request): + raise InvalidRequestError('Replay attack') + + +def generate_id_token( + token, user_info, key, iss, aud, alg='RS256', exp=3600, + nonce=None, auth_time=None, code=None): + + now = int(time.time()) + if auth_time is None: + auth_time = now + + payload = { + 'iss': iss, + 'aud': aud, + 'iat': now, + 'exp': now + exp, + 'auth_time': auth_time, + } + if nonce: + payload['nonce'] = nonce + + if code: + payload['c_hash'] = to_native(create_half_hash(code, alg)) + + access_token = token.get('access_token') + if access_token: + payload['at_hash'] = to_native(create_half_hash(access_token, alg)) + + payload.update(user_info) + return to_native(jwt.encode({'alg': alg}, payload, key)) + + +def create_response_mode_response(redirect_uri, params, response_mode): + if response_mode == 'form_post': + tpl = ( + 'Redirecting' + '' + '
{}
' + ) + inputs = ''.join([ + ''.format( + quote_url(k), quote_url(v)) + for k, v in params + ]) + body = tpl.format(quote_url(redirect_uri), inputs) + return 200, body, [('Content-Type', 'text/html; charset=utf-8')] + + if response_mode == 'query': + uri = add_params_to_uri(redirect_uri, params, fragment=False) + elif response_mode == 'fragment': + uri = add_params_to_uri(redirect_uri, params, fragment=True) + else: + raise InvalidRequestError('Invalid "response_mode" value') + + return 302, '', [('Location', uri)] + + +def _guess_prompt_value(end_user, prompts, redirect_uri, redirect_fragment): + # http://openid.net/specs/openid-connect-core-1_0.html#AuthRequest + + if not end_user and 'login' in prompts: + return 'login' + + if 'consent' in prompts: + if not end_user: + raise ConsentRequiredError( + redirect_uri=redirect_uri, + redirect_fragment=redirect_fragment) + return 'consent' + elif 'select_account' in prompts: + if not end_user: + raise AccountSelectionRequiredError( + redirect_uri=redirect_uri, + redirect_fragment=redirect_fragment) + return 'select_account' diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/models.py new file mode 100644 index 0000000000000000000000000000000000000000..5f414050757958eb601b1aa68fec50d768fffe38 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/models.py @@ -0,0 +1,13 @@ +from authlib.oauth2.rfc6749 import ( + AuthorizationCodeMixin as _AuthorizationCodeMixin +) + + +class AuthorizationCodeMixin(_AuthorizationCodeMixin): + def get_nonce(self): + """Get "nonce" value of the authorization code object.""" + raise NotImplementedError() + + def get_auth_time(self): + """Get "auth_time" value of the authorization code object.""" + raise NotImplementedError() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/util.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/util.py new file mode 100644 index 0000000000000000000000000000000000000000..6df005d25fdff234b661bdf807d17384aa99aadb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/core/util.py @@ -0,0 +1,12 @@ +import hashlib +from authlib.common.encoding import to_bytes, urlsafe_b64encode + + +def create_half_hash(s, alg): + hash_type = f'sha{alg[2:]}' + hash_alg = getattr(hashlib, hash_type, None) + if not hash_alg: + return None + data_digest = hash_alg(to_bytes(s)).digest() + slice_index = int(len(data_digest) / 2) + return urlsafe_b64encode(data_digest[:slice_index]) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/discovery/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/discovery/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e76401bdd1509e574c95d287a575f7ae11c7dde --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/discovery/__init__.py @@ -0,0 +1,13 @@ +""" + authlib.oidc.discover + ~~~~~~~~~~~~~~~~~~~~~ + + OpenID Connect Discovery 1.0 Implementation. + + https://openid.net/specs/openid-connect-discovery-1_0.html +""" + +from .models import OpenIDProviderMetadata +from .well_known import get_well_known_url + +__all__ = ['OpenIDProviderMetadata', 'get_well_known_url'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/discovery/models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/discovery/models.py new file mode 100644 index 0000000000000000000000000000000000000000..d9329efdaea46ce673e059560b456af8e64ac3a1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/discovery/models.py @@ -0,0 +1,283 @@ +from authlib.oauth2.rfc8414 import AuthorizationServerMetadata +from authlib.oauth2.rfc8414.models import validate_array_value + + +class OpenIDProviderMetadata(AuthorizationServerMetadata): + REGISTRY_KEYS = [ + 'issuer', 'authorization_endpoint', 'token_endpoint', + 'jwks_uri', 'registration_endpoint', 'scopes_supported', + 'response_types_supported', 'response_modes_supported', + 'grant_types_supported', + 'token_endpoint_auth_methods_supported', + 'token_endpoint_auth_signing_alg_values_supported', + 'service_documentation', 'ui_locales_supported', + 'op_policy_uri', 'op_tos_uri', + + # added by OpenID + 'acr_values_supported', 'subject_types_supported', + 'id_token_signing_alg_values_supported', + 'id_token_encryption_alg_values_supported', + 'id_token_encryption_enc_values_supported', + 'userinfo_signing_alg_values_supported', + 'userinfo_encryption_alg_values_supported', + 'userinfo_encryption_enc_values_supported', + 'request_object_signing_alg_values_supported', + 'request_object_encryption_alg_values_supported', + 'request_object_encryption_enc_values_supported', + 'display_values_supported', + 'claim_types_supported', + 'claims_supported', + 'claims_locales_supported', + 'claims_parameter_supported', + 'request_parameter_supported', + 'request_uri_parameter_supported', + 'require_request_uri_registration', + + # not defined by OpenID + # 'revocation_endpoint', + # 'revocation_endpoint_auth_methods_supported', + # 'revocation_endpoint_auth_signing_alg_values_supported', + # 'introspection_endpoint', + # 'introspection_endpoint_auth_methods_supported', + # 'introspection_endpoint_auth_signing_alg_values_supported', + # 'code_challenge_methods_supported', + ] + + def validate_jwks_uri(self): + # REQUIRED in OpenID Connect + jwks_uri = self.get('jwks_uri') + if jwks_uri is None: + raise ValueError('"jwks_uri" is required') + return super().validate_jwks_uri() + + def validate_acr_values_supported(self): + """OPTIONAL. JSON array containing a list of the Authentication + Context Class References that this OP supports. + """ + validate_array_value(self, 'acr_values_supported') + + def validate_subject_types_supported(self): + """REQUIRED. JSON array containing a list of the Subject Identifier + types that this OP supports. Valid types include pairwise and public. + """ + # 1. REQUIRED + values = self.get('subject_types_supported') + if values is None: + raise ValueError('"subject_types_supported" is required') + + # 2. JSON array + if not isinstance(values, list): + raise ValueError('"subject_types_supported" MUST be JSON array') + + # 3. Valid types include pairwise and public + valid_types = {'pairwise', 'public'} + if not valid_types.issuperset(set(values)): + raise ValueError( + '"subject_types_supported" contains invalid values') + + def validate_id_token_signing_alg_values_supported(self): + """REQUIRED. JSON array containing a list of the JWS signing + algorithms (alg values) supported by the OP for the ID Token to + encode the Claims in a JWT [JWT]. The algorithm RS256 MUST be + included. The value none MAY be supported, but MUST NOT be used + unless the Response Type used returns no ID Token from the + Authorization Endpoint (such as when using the Authorization + Code Flow). + """ + # 1. REQUIRED + values = self.get('id_token_signing_alg_values_supported') + if values is None: + raise ValueError('"id_token_signing_alg_values_supported" is required') + + # 2. JSON array + if not isinstance(values, list): + raise ValueError('"id_token_signing_alg_values_supported" MUST be JSON array') + + # 3. The algorithm RS256 MUST be included + if 'RS256' not in values: + raise ValueError( + '"RS256" MUST be included in "id_token_signing_alg_values_supported"') + + def validate_id_token_encryption_alg_values_supported(self): + """OPTIONAL. JSON array containing a list of the JWE encryption + algorithms (alg values) supported by the OP for the ID Token to + encode the Claims in a JWT. + """ + validate_array_value(self, 'id_token_encryption_alg_values_supported') + + def validate_id_token_encryption_enc_values_supported(self): + """OPTIONAL. JSON array containing a list of the JWE encryption + algorithms (enc values) supported by the OP for the ID Token to + encode the Claims in a JWT. + """ + validate_array_value(self, 'id_token_encryption_enc_values_supported') + + def validate_userinfo_signing_alg_values_supported(self): + """OPTIONAL. JSON array containing a list of the JWS signing + algorithms (alg values) [JWA] supported by the UserInfo Endpoint + to encode the Claims in a JWT. The value none MAY be included. + """ + validate_array_value(self, 'userinfo_signing_alg_values_supported') + + def validate_userinfo_encryption_alg_values_supported(self): + """OPTIONAL. JSON array containing a list of the JWE encryption + algorithms (alg values) [JWA] supported by the UserInfo Endpoint + to encode the Claims in a JWT. + """ + validate_array_value(self, 'userinfo_encryption_alg_values_supported') + + def validate_userinfo_encryption_enc_values_supported(self): + """OPTIONAL. JSON array containing a list of the JWE encryption + algorithms (enc values) [JWA] supported by the UserInfo Endpoint + to encode the Claims in a JWT. + """ + validate_array_value(self, 'userinfo_encryption_enc_values_supported') + + def validate_request_object_signing_alg_values_supported(self): + """OPTIONAL. JSON array containing a list of the JWS signing + algorithms (alg values) supported by the OP for Request Objects, + which are described in Section 6.1 of OpenID Connect Core 1.0. + These algorithms are used both when the Request Object is passed + by value (using the request parameter) and when it is passed by + reference (using the request_uri parameter). Servers SHOULD support + none and RS256. + """ + values = self.get('request_object_signing_alg_values_supported') + if not values: + return + + if not isinstance(values, list): + raise ValueError('"request_object_signing_alg_values_supported" MUST be JSON array') + + # Servers SHOULD support none and RS256 + if 'none' not in values or 'RS256' not in values: + raise ValueError( + '"request_object_signing_alg_values_supported" ' + 'SHOULD support none and RS256') + + def validate_request_object_encryption_alg_values_supported(self): + """OPTIONAL. JSON array containing a list of the JWE encryption + algorithms (alg values) supported by the OP for Request Objects. + These algorithms are used both when the Request Object is passed + by value and when it is passed by reference. + """ + validate_array_value(self, 'request_object_encryption_alg_values_supported') + + def validate_request_object_encryption_enc_values_supported(self): + """OPTIONAL. JSON array containing a list of the JWE encryption + algorithms (enc values) supported by the OP for Request Objects. + These algorithms are used both when the Request Object is passed + by value and when it is passed by reference. + """ + validate_array_value(self, 'request_object_encryption_enc_values_supported') + + def validate_display_values_supported(self): + """OPTIONAL. JSON array containing a list of the display parameter + values that the OpenID Provider supports. These values are described + in Section 3.1.2.1 of OpenID Connect Core 1.0. + """ + values = self.get('display_values_supported') + if not values: + return + + if not isinstance(values, list): + raise ValueError('"display_values_supported" MUST be JSON array') + + valid_values = {'page', 'popup', 'touch', 'wap'} + if not valid_values.issuperset(set(values)): + raise ValueError('"display_values_supported" contains invalid values') + + def validate_claim_types_supported(self): + """OPTIONAL. JSON array containing a list of the Claim Types that + the OpenID Provider supports. These Claim Types are described in + Section 5.6 of OpenID Connect Core 1.0. Values defined by this + specification are normal, aggregated, and distributed. If omitted, + the implementation supports only normal Claims. + """ + values = self.get('claim_types_supported') + if not values: + return + + if not isinstance(values, list): + raise ValueError('"claim_types_supported" MUST be JSON array') + + valid_values = {'normal', 'aggregated', 'distributed'} + if not valid_values.issuperset(set(values)): + raise ValueError('"claim_types_supported" contains invalid values') + + def validate_claims_supported(self): + """RECOMMENDED. JSON array containing a list of the Claim Names + of the Claims that the OpenID Provider MAY be able to supply values + for. Note that for privacy or other reasons, this might not be an + exhaustive list. + """ + validate_array_value(self, 'claims_supported') + + def validate_claims_locales_supported(self): + """OPTIONAL. Languages and scripts supported for values in Claims + being returned, represented as a JSON array of BCP47 [RFC5646] + language tag values. Not all languages and scripts are necessarily + supported for all Claim values. + """ + validate_array_value(self, 'claims_locales_supported') + + def validate_claims_parameter_supported(self): + """OPTIONAL. Boolean value specifying whether the OP supports use of + the claims parameter, with true indicating support. If omitted, the + default value is false. + """ + _validate_boolean_value(self, 'claims_parameter_supported') + + def validate_request_parameter_supported(self): + """OPTIONAL. Boolean value specifying whether the OP supports use of + the request parameter, with true indicating support. If omitted, the + default value is false. + """ + _validate_boolean_value(self, 'request_parameter_supported') + + def validate_request_uri_parameter_supported(self): + """OPTIONAL. Boolean value specifying whether the OP supports use of + the request_uri parameter, with true indicating support. If omitted, + the default value is true. + """ + _validate_boolean_value(self, 'request_uri_parameter_supported') + + def validate_require_request_uri_registration(self): + """OPTIONAL. Boolean value specifying whether the OP requires any + request_uri values used to be pre-registered using the request_uris + registration parameter. Pre-registration is REQUIRED when the value + is true. If omitted, the default value is false. + """ + _validate_boolean_value(self, 'require_request_uri_registration') + + @property + def claim_types_supported(self): + # If omitted, the implementation supports only normal Claims + return self.get('claim_types_supported', ['normal']) + + @property + def claims_parameter_supported(self): + # If omitted, the default value is false. + return self.get('claims_parameter_supported', False) + + @property + def request_parameter_supported(self): + # If omitted, the default value is false. + return self.get('request_parameter_supported', False) + + @property + def request_uri_parameter_supported(self): + # If omitted, the default value is true. + return self.get('request_uri_parameter_supported', True) + + @property + def require_request_uri_registration(self): + # If omitted, the default value is false. + return self.get('require_request_uri_registration', False) + + +def _validate_boolean_value(metadata, key): + if key not in metadata: + return + if metadata[key] not in (True, False): + raise ValueError(f'"{key}" MUST be boolean') diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/discovery/well_known.py b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/discovery/well_known.py new file mode 100644 index 0000000000000000000000000000000000000000..e3087a143f6e9f86172659cd4f070b5ea901504e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/authlib/oidc/discovery/well_known.py @@ -0,0 +1,17 @@ +from authlib.common.urls import urlparse + + +def get_well_known_url(issuer, external=False): + """Get well-known URI with issuer via Section 4.1. + + :param issuer: URL of the issuer + :param external: return full external url or not + :return: URL + """ + # https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest + if external: + return issuer.rstrip('/') + '/.well-known/openid-configuration' + + parsed = urlparse.urlparse(issuer) + path = parsed.path + return path.rstrip('/') + '/.well-known/openid-configuration' diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..56a28d94eccfb0c39a5a92c2672d1a43da544c7d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/__init__.py @@ -0,0 +1,191 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +from typing import TypeVar, Generic, Dict, Any, Tuple, List, Optional, overload, TYPE_CHECKING, Union + +HTTPResponseType = TypeVar("HTTPResponseType", covariant=True) # pylint: disable=typevar-name-incorrect-variance +HTTPRequestType = TypeVar("HTTPRequestType", covariant=True) # pylint: disable=typevar-name-incorrect-variance + +if TYPE_CHECKING: + from .transport import HttpTransport, AsyncHttpTransport + + TransportType = Union[HttpTransport[Any, Any], AsyncHttpTransport[Any, Any]] + + +class PipelineContext(Dict[str, Any]): + """A context object carried by the pipeline request and response containers. + + This is transport specific and can contain data persisted between + pipeline requests (for example reusing an open connection pool or "session"), + as well as used by the SDK developer to carry arbitrary data through + the pipeline. + + :param transport: The HTTP transport type. + :type transport: ~azure.core.pipeline.transport.HttpTransport or ~azure.core.pipeline.transport.AsyncHttpTransport + :param any kwargs: Developer-defined keyword arguments. + """ + + _PICKLE_CONTEXT = {"deserialized_data"} + + def __init__( + self, transport: Optional["TransportType"], **kwargs: Any + ) -> None: # pylint: disable=super-init-not-called + self.transport: Optional["TransportType"] = transport + self.options = kwargs + self._protected = ["transport", "options"] + + def __getstate__(self) -> Dict[str, Any]: + state = self.__dict__.copy() + # Remove the unpicklable entries. + del state["transport"] + return state + + def __reduce__(self) -> Tuple[Any, ...]: + reduced = super(PipelineContext, self).__reduce__() + saved_context = {} + for key, value in self.items(): + if key in self._PICKLE_CONTEXT: + saved_context[key] = value + # 1 is for from __reduce__ spec of pickle (generic args for recreation) + # 2 is how dict is implementing __reduce__ (dict specific) + # tuple are read-only, we use a list in the meantime + reduced_as_list: List[Any] = list(reduced) + dict_reduced_result = list(reduced_as_list[1]) + dict_reduced_result[2] = saved_context + reduced_as_list[1] = tuple(dict_reduced_result) + return tuple(reduced_as_list) + + def __setstate__(self, state: Dict[str, Any]) -> None: + self.__dict__.update(state) + # Re-create the unpickable entries + self.transport = None + + def __setitem__(self, key: str, item: Any) -> None: + # If reloaded from pickle, _protected might not be here until restored by pickle + # this explains the hasattr test + if hasattr(self, "_protected") and key in self._protected: + raise ValueError("Context value {} cannot be overwritten.".format(key)) + return super(PipelineContext, self).__setitem__(key, item) + + def __delitem__(self, key: str) -> None: + if key in self._protected: + raise ValueError("Context value {} cannot be deleted.".format(key)) + return super(PipelineContext, self).__delitem__(key) + + def clear(self) -> None: # pylint: disable=docstring-missing-return, docstring-missing-rtype + """Context objects cannot be cleared. + + :raises: TypeError + """ + raise TypeError("Context objects cannot be cleared.") + + def update( # pylint: disable=docstring-missing-return, docstring-missing-rtype, docstring-missing-param + self, *args: Any, **kwargs: Any + ) -> None: + """Context objects cannot be updated. + + :raises: TypeError + """ + raise TypeError("Context objects cannot be updated.") + + @overload + def pop(self, __key: str) -> Any: + ... + + @overload + def pop(self, __key: str, __default: Optional[Any]) -> Any: + ... + + def pop(self, *args: Any) -> Any: + """Removes specified key and returns the value. + + :param args: The key to remove. + :type args: str + :return: The value for this key. + :rtype: any + :raises: ValueError If the key is in the protected list. + """ + if args and args[0] in self._protected: + raise ValueError("Context value {} cannot be popped.".format(args[0])) + return super(PipelineContext, self).pop(*args) + + +class PipelineRequest(Generic[HTTPRequestType]): + """A pipeline request object. + + Container for moving the HttpRequest through the pipeline. + Universal for all transports, both synchronous and asynchronous. + + :param http_request: The request object. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :param context: Contains the context - data persisted between pipeline requests. + :type context: ~azure.core.pipeline.PipelineContext + """ + + def __init__(self, http_request: HTTPRequestType, context: PipelineContext) -> None: + self.http_request = http_request + self.context = context + + +class PipelineResponse(Generic[HTTPRequestType, HTTPResponseType]): + """A pipeline response object. + + The PipelineResponse interface exposes an HTTP response object as it returns through the pipeline of Policy objects. + This ensures that Policy objects have access to the HTTP response. + + This also has a "context" object where policy can put additional fields. + Policy SHOULD update the "context" with additional post-processed field if they create them. + However, nothing prevents a policy to actually sub-class this class a return it instead of the initial instance. + + :param http_request: The request object. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :param http_response: The response object. + :type http_response: ~azure.core.pipeline.transport.HttpResponse + :param context: Contains the context - data persisted between pipeline requests. + :type context: ~azure.core.pipeline.PipelineContext + """ + + def __init__( + self, + http_request: HTTPRequestType, + http_response: HTTPResponseType, + context: PipelineContext, + ) -> None: + self.http_request = http_request + self.http_response = http_response + self.context = context + + +from ._base import Pipeline # pylint: disable=wrong-import-position +from ._base_async import AsyncPipeline # pylint: disable=wrong-import-position + +__all__ = [ + "Pipeline", + "PipelineRequest", + "PipelineResponse", + "PipelineContext", + "AsyncPipeline", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..025cb5df6f744e79c9943b75733a7328508e3793 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_base.py @@ -0,0 +1,230 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from __future__ import annotations +import logging +from typing import Generic, TypeVar, Union, Any, List, Dict, Optional, Iterable, ContextManager +from azure.core.pipeline import ( + PipelineRequest, + PipelineResponse, + PipelineContext, +) +from azure.core.pipeline.policies import HTTPPolicy, SansIOHTTPPolicy +from ._tools import await_result as _await_result +from .transport import HttpTransport + +HTTPResponseType = TypeVar("HTTPResponseType") +HTTPRequestType = TypeVar("HTTPRequestType") + +_LOGGER = logging.getLogger(__name__) + + +def cleanup_kwargs_for_transport(kwargs: Dict[str, str]) -> None: + """Remove kwargs that are not meant for the transport layer. + :param kwargs: The keyword arguments. + :type kwargs: dict + + "insecure_domain_change" is used to indicate that a redirect + has occurred to a different domain. This tells the SensitiveHeaderCleanupPolicy + to clean up sensitive headers. We need to remove it before sending the request + to the transport layer. This code is needed to handle the case that the + SensitiveHeaderCleanupPolicy is not added into the pipeline and "insecure_domain_change" is not popped. + "enable_cae" is added to the `get_token` method of the `TokenCredential` protocol. + """ + kwargs_to_remove = ["insecure_domain_change", "enable_cae"] + if not kwargs: + return + for key in kwargs_to_remove: + kwargs.pop(key, None) + + +class _SansIOHTTPPolicyRunner(HTTPPolicy[HTTPRequestType, HTTPResponseType]): + """Sync implementation of the SansIO policy. + + Modifies the request and sends to the next policy in the chain. + + :param policy: A SansIO policy. + :type policy: ~azure.core.pipeline.policies.SansIOHTTPPolicy + """ + + def __init__(self, policy: SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]) -> None: + super(_SansIOHTTPPolicyRunner, self).__init__() + self._policy = policy + + def send(self, request: PipelineRequest[HTTPRequestType]) -> PipelineResponse[HTTPRequestType, HTTPResponseType]: + """Modifies the request and sends to the next policy in the chain. + + :param request: The PipelineRequest object. + :type request: ~azure.core.pipeline.PipelineRequest + :return: The PipelineResponse object. + :rtype: ~azure.core.pipeline.PipelineResponse + """ + _await_result(self._policy.on_request, request) + try: + response = self.next.send(request) + except Exception: # pylint: disable=broad-except + _await_result(self._policy.on_exception, request) + raise + else: + _await_result(self._policy.on_response, request, response) + return response + + +class _TransportRunner(HTTPPolicy[HTTPRequestType, HTTPResponseType]): + """Transport runner. + + Uses specified HTTP transport type to send request and returns response. + + :param sender: The Http Transport instance. + :type sender: ~azure.core.pipeline.transport.HttpTransport + """ + + def __init__(self, sender: HttpTransport[HTTPRequestType, HTTPResponseType]) -> None: + super(_TransportRunner, self).__init__() + self._sender = sender + + def send(self, request: PipelineRequest[HTTPRequestType]) -> PipelineResponse[HTTPRequestType, HTTPResponseType]: + """HTTP transport send method. + + :param request: The PipelineRequest object. + :type request: ~azure.core.pipeline.PipelineRequest + :return: The PipelineResponse object. + :rtype: ~azure.core.pipeline.PipelineResponse + """ + cleanup_kwargs_for_transport(request.context.options) + return PipelineResponse( + request.http_request, + self._sender.send(request.http_request, **request.context.options), + context=request.context, + ) + + +class Pipeline(ContextManager["Pipeline"], Generic[HTTPRequestType, HTTPResponseType]): + """A pipeline implementation. + + This is implemented as a context manager, that will activate the context + of the HTTP sender. The transport is the last node in the pipeline. + + :param transport: The Http Transport instance + :type transport: ~azure.core.pipeline.transport.HttpTransport + :param list policies: List of configured policies. + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_sync.py + :start-after: [START build_pipeline] + :end-before: [END build_pipeline] + :language: python + :dedent: 4 + :caption: Builds the pipeline for synchronous transport. + """ + + def __init__( + self, + transport: HttpTransport[HTTPRequestType, HTTPResponseType], + policies: Optional[ + Iterable[ + Union[ + HTTPPolicy[HTTPRequestType, HTTPResponseType], SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType] + ] + ] + ] = None, + ) -> None: + self._impl_policies: List[HTTPPolicy[HTTPRequestType, HTTPResponseType]] = [] + self._transport = transport + + for policy in policies or []: + if isinstance(policy, SansIOHTTPPolicy): + self._impl_policies.append(_SansIOHTTPPolicyRunner(policy)) + elif policy: + self._impl_policies.append(policy) + for index in range(len(self._impl_policies) - 1): + self._impl_policies[index].next = self._impl_policies[index + 1] + if self._impl_policies: + self._impl_policies[-1].next = _TransportRunner(self._transport) + + def __enter__(self) -> Pipeline[HTTPRequestType, HTTPResponseType]: + self._transport.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: # pylint: disable=arguments-differ + self._transport.__exit__(*exc_details) + + @staticmethod + def _prepare_multipart_mixed_request(request: HTTPRequestType) -> None: + """Will execute the multipart policies. + + Does nothing if "set_multipart_mixed" was never called. + + :param request: The request object. + :type request: ~azure.core.rest.HttpRequest + """ + multipart_mixed_info = request.multipart_mixed_info # type: ignore + if not multipart_mixed_info: + return + + requests: List[HTTPRequestType] = multipart_mixed_info[0] + policies: List[SansIOHTTPPolicy] = multipart_mixed_info[1] + pipeline_options: Dict[str, Any] = multipart_mixed_info[3] + + # Apply on_requests concurrently to all requests + import concurrent.futures + + def prepare_requests(req): + if req.multipart_mixed_info: + # Recursively update changeset "sub requests" + Pipeline._prepare_multipart_mixed_request(req) + context = PipelineContext(None, **pipeline_options) + pipeline_request = PipelineRequest(req, context) + for policy in policies: + _await_result(policy.on_request, pipeline_request) + + with concurrent.futures.ThreadPoolExecutor() as executor: + # List comprehension to raise exceptions if happened + [ # pylint: disable=expression-not-assigned, unnecessary-comprehension + _ for _ in executor.map(prepare_requests, requests) + ] + + def _prepare_multipart(self, request: HTTPRequestType) -> None: + # This code is fine as long as HTTPRequestType is actually + # azure.core.pipeline.transport.HTTPRequest, bu we don't check it in here + # since we didn't see (yet) pipeline usage where it's not this actual instance + # class used + self._prepare_multipart_mixed_request(request) + request.prepare_multipart_body() # type: ignore + + def run(self, request: HTTPRequestType, **kwargs: Any) -> PipelineResponse[HTTPRequestType, HTTPResponseType]: + """Runs the HTTP Request through the chained policies. + + :param request: The HTTP request object. + :type request: ~azure.core.pipeline.transport.HttpRequest + :return: The PipelineResponse object + :rtype: ~azure.core.pipeline.PipelineResponse + """ + self._prepare_multipart(request) + context = PipelineContext(self._transport, **kwargs) + pipeline_request: PipelineRequest[HTTPRequestType] = PipelineRequest(request, context) + first_node = self._impl_policies[0] if self._impl_policies else _TransportRunner(self._transport) + return first_node.send(pipeline_request) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_base_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_base_async.py new file mode 100644 index 0000000000000000000000000000000000000000..c12e1be4ce4a875f481cfca4b5483986af11caa9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_base_async.py @@ -0,0 +1,221 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from __future__ import annotations +from types import TracebackType +from typing import Any, Union, Generic, TypeVar, List, Dict, Optional, Iterable, Type +from typing_extensions import AsyncContextManager + +from azure.core.pipeline import PipelineRequest, PipelineResponse, PipelineContext +from azure.core.pipeline.policies import AsyncHTTPPolicy, SansIOHTTPPolicy +from ._tools_async import await_result as _await_result +from ._base import cleanup_kwargs_for_transport +from .transport import AsyncHttpTransport + +AsyncHTTPResponseType = TypeVar("AsyncHTTPResponseType") +HTTPRequestType = TypeVar("HTTPRequestType") + + +class _SansIOAsyncHTTPPolicyRunner( + AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType] +): # pylint: disable=unsubscriptable-object + """Async implementation of the SansIO policy. + + Modifies the request and sends to the next policy in the chain. + + :param policy: A SansIO policy. + :type policy: ~azure.core.pipeline.policies.SansIOHTTPPolicy + """ + + def __init__(self, policy: SansIOHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]) -> None: + super(_SansIOAsyncHTTPPolicyRunner, self).__init__() + self._policy = policy + + async def send( + self, request: PipelineRequest[HTTPRequestType] + ) -> PipelineResponse[HTTPRequestType, AsyncHTTPResponseType]: + """Modifies the request and sends to the next policy in the chain. + + :param request: The PipelineRequest object. + :type request: ~azure.core.pipeline.PipelineRequest + :return: The PipelineResponse object. + :rtype: ~azure.core.pipeline.PipelineResponse + """ + await _await_result(self._policy.on_request, request) + response: PipelineResponse[HTTPRequestType, AsyncHTTPResponseType] + try: + response = await self.next.send(request) + except Exception: # pylint: disable=broad-except + await _await_result(self._policy.on_exception, request) + raise + else: + await _await_result(self._policy.on_response, request, response) + return response + + +class _AsyncTransportRunner( + AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType] +): # pylint: disable=unsubscriptable-object + """Async Transport runner. + + Uses specified HTTP transport type to send request and returns response. + + :param sender: The async Http Transport instance. + :type sender: ~azure.core.pipeline.transport.AsyncHttpTransport + """ + + def __init__(self, sender: AsyncHttpTransport[HTTPRequestType, AsyncHTTPResponseType]) -> None: + super(_AsyncTransportRunner, self).__init__() + self._sender = sender + + async def send( + self, request: PipelineRequest[HTTPRequestType] + ) -> PipelineResponse[HTTPRequestType, AsyncHTTPResponseType]: + """Async HTTP transport send method. + + :param request: The PipelineRequest object. + :type request: ~azure.core.pipeline.PipelineRequest + :return: The PipelineResponse object. + :rtype: ~azure.core.pipeline.PipelineResponse + """ + cleanup_kwargs_for_transport(request.context.options) + return PipelineResponse( + request.http_request, + await self._sender.send(request.http_request, **request.context.options), + request.context, + ) + + +class AsyncPipeline(AsyncContextManager["AsyncPipeline"], Generic[HTTPRequestType, AsyncHTTPResponseType]): + """Async pipeline implementation. + + This is implemented as a context manager, that will activate the context + of the HTTP sender. + + :param transport: The async Http Transport instance. + :type transport: ~azure.core.pipeline.transport.AsyncHttpTransport + :param list policies: List of configured policies. + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_async.py + :start-after: [START build_async_pipeline] + :end-before: [END build_async_pipeline] + :language: python + :dedent: 4 + :caption: Builds the async pipeline for asynchronous transport. + """ + + def __init__( + self, + transport: AsyncHttpTransport[HTTPRequestType, AsyncHTTPResponseType], + policies: Optional[ + Iterable[ + Union[ + AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType], + SansIOHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType], + ] + ] + ] = None, + ) -> None: + self._impl_policies: List[AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]] = [] + self._transport = transport + + for policy in policies or []: + if isinstance(policy, SansIOHTTPPolicy): + self._impl_policies.append(_SansIOAsyncHTTPPolicyRunner(policy)) + elif policy: + self._impl_policies.append(policy) + for index in range(len(self._impl_policies) - 1): + self._impl_policies[index].next = self._impl_policies[index + 1] + if self._impl_policies: + self._impl_policies[-1].next = _AsyncTransportRunner(self._transport) + + async def __aenter__(self) -> AsyncPipeline[HTTPRequestType, AsyncHTTPResponseType]: + await self._transport.__aenter__() + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ) -> None: + await self._transport.__aexit__(exc_type, exc_value, traceback) + + async def _prepare_multipart_mixed_request(self, request: HTTPRequestType) -> None: + """Will execute the multipart policies. + + Does nothing if "set_multipart_mixed" was never called. + + :param request: The HTTP request object. + :type request: ~azure.core.rest.HttpRequest + """ + multipart_mixed_info = request.multipart_mixed_info # type: ignore + if not multipart_mixed_info: + return + + requests: List[HTTPRequestType] = multipart_mixed_info[0] + policies: List[SansIOHTTPPolicy] = multipart_mixed_info[1] + pipeline_options: Dict[str, Any] = multipart_mixed_info[3] + + async def prepare_requests(req): + if req.multipart_mixed_info: + # Recursively update changeset "sub requests" + await self._prepare_multipart_mixed_request(req) + context = PipelineContext(None, **pipeline_options) + pipeline_request = PipelineRequest(req, context) + for policy in policies: + await _await_result(policy.on_request, pipeline_request) + + # Not happy to make this code asyncio specific, but that's multipart only for now + # If we need trio and multipart, let's reinvesitgate that later + import asyncio + + await asyncio.gather(*[prepare_requests(req) for req in requests]) + + async def _prepare_multipart(self, request: HTTPRequestType) -> None: + # This code is fine as long as HTTPRequestType is actually + # azure.core.pipeline.transport.HTTPRequest, bu we don't check it in here + # since we didn't see (yet) pipeline usage where it's not this actual instance + # class used + await self._prepare_multipart_mixed_request(request) + request.prepare_multipart_body() # type: ignore + + async def run( + self, request: HTTPRequestType, **kwargs: Any + ) -> PipelineResponse[HTTPRequestType, AsyncHTTPResponseType]: + """Runs the HTTP Request through the chained policies. + + :param request: The HTTP request object. + :type request: ~azure.core.pipeline.transport.HttpRequest + :return: The PipelineResponse object. + :rtype: ~azure.core.pipeline.PipelineResponse + """ + await self._prepare_multipart(request) + context = PipelineContext(self._transport, **kwargs) + pipeline_request = PipelineRequest(request, context) + first_node = self._impl_policies[0] if self._impl_policies else _AsyncTransportRunner(self._transport) + return await first_node.send(pipeline_request) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_tools.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b8545f0d8f9edc9d0b6aaf1a2e54746c80497a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_tools.py @@ -0,0 +1,84 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from __future__ import annotations +from typing import TYPE_CHECKING, Union, Callable, TypeVar +from typing_extensions import TypeGuard, ParamSpec + +if TYPE_CHECKING: + from azure.core.rest import HttpResponse, HttpRequest, AsyncHttpResponse + + +P = ParamSpec("P") +T = TypeVar("T") + + +def await_result(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: + """If func returns an awaitable, raise that this runner can't handle it. + + :param func: The function to run. + :type func: callable + :param args: The positional arguments to pass to the function. + :type args: list + :rtype: any + :return: The result of the function + :raises: TypeError + """ + result = func(*args, **kwargs) + if hasattr(result, "__await__"): + raise TypeError("Policy {} returned awaitable object in non-async pipeline.".format(func)) + return result + + +def is_rest(obj: object) -> TypeGuard[Union[HttpRequest, HttpResponse, AsyncHttpResponse]]: + """Return whether a request or a response is a rest request / response. + + Checking whether the response has the object content can sometimes result + in a ResponseNotRead error if you're checking the value on a response + that has not been read in yet. To get around this, we also have added + a check for is_stream_consumed, which is an exclusive property on our new responses. + + :param obj: The object to check. + :type obj: any + :rtype: bool + :return: Whether the object is a rest request / response. + """ + return hasattr(obj, "is_stream_consumed") or hasattr(obj, "content") + + +def handle_non_stream_rest_response(response: HttpResponse) -> None: + """Handle reading and closing of non stream rest responses. + For our new rest responses, we have to call .read() and .close() for our non-stream + responses. This way, we load in the body for users to access. + + :param response: The response to read and close. + :type response: ~azure.core.rest.HttpResponse + """ + try: + response.read() + response.close() + except Exception as exc: + response.close() + raise exc diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_tools_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_tools_async.py new file mode 100644 index 0000000000000000000000000000000000000000..3395b5cbbbe720b3b51b506a7b8dd63e71ef4955 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/_tools_async.py @@ -0,0 +1,75 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING, Callable, TypeVar, Awaitable, Union, overload +from typing_extensions import ParamSpec + +if TYPE_CHECKING: + from ..rest import AsyncHttpResponse as RestAsyncHttpResponse + +P = ParamSpec("P") +T = TypeVar("T") + + +@overload +async def await_result(func: Callable[P, Awaitable[T]], *args: P.args, **kwargs: P.kwargs) -> T: + ... + + +@overload +async def await_result(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: + ... + + +async def await_result(func: Callable[P, Union[T, Awaitable[T]]], *args: P.args, **kwargs: P.kwargs) -> T: + """If func returns an awaitable, await it. + + :param func: The function to run. + :type func: callable + :param args: The positional arguments to pass to the function. + :type args: list + :rtype: any + :return: The result of the function + """ + result = func(*args, **kwargs) + if isinstance(result, Awaitable): + return await result + return result + + +async def handle_no_stream_rest_response(response: "RestAsyncHttpResponse") -> None: + """Handle reading and closing of non stream rest responses. + For our new rest responses, we have to call .read() and .close() for our non-stream + responses. This way, we load in the body for users to access. + + :param response: The response to read and close. + :type response: ~azure.core.rest.AsyncHttpResponse + """ + try: + await response.read() + await response.close() + except Exception as exc: + await response.close() + raise exc diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c47ee8d66f3611f2069479fa7a7336f52a3975c8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/__init__.py @@ -0,0 +1,76 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +from ._base import HTTPPolicy, SansIOHTTPPolicy, RequestHistory +from ._authentication import ( + BearerTokenCredentialPolicy, + AzureKeyCredentialPolicy, + AzureSasCredentialPolicy, +) +from ._custom_hook import CustomHookPolicy +from ._redirect import RedirectPolicy +from ._retry import RetryPolicy, RetryMode +from ._distributed_tracing import DistributedTracingPolicy +from ._universal import ( + HeadersPolicy, + UserAgentPolicy, + NetworkTraceLoggingPolicy, + ContentDecodePolicy, + ProxyPolicy, + HttpLoggingPolicy, + RequestIdPolicy, +) +from ._base_async import AsyncHTTPPolicy +from ._authentication_async import AsyncBearerTokenCredentialPolicy +from ._redirect_async import AsyncRedirectPolicy +from ._retry_async import AsyncRetryPolicy +from ._sensitive_header_cleanup_policy import SensitiveHeaderCleanupPolicy + +__all__ = [ + "HTTPPolicy", + "SansIOHTTPPolicy", + "BearerTokenCredentialPolicy", + "AzureKeyCredentialPolicy", + "AzureSasCredentialPolicy", + "HeadersPolicy", + "UserAgentPolicy", + "NetworkTraceLoggingPolicy", + "ContentDecodePolicy", + "RetryMode", + "RetryPolicy", + "RedirectPolicy", + "ProxyPolicy", + "CustomHookPolicy", + "DistributedTracingPolicy", + "RequestHistory", + "HttpLoggingPolicy", + "RequestIdPolicy", + "AsyncHTTPPolicy", + "AsyncBearerTokenCredentialPolicy", + "AsyncRedirectPolicy", + "AsyncRetryPolicy", + "SensitiveHeaderCleanupPolicy", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_authentication.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_authentication.py new file mode 100644 index 0000000000000000000000000000000000000000..1a78be3cfbc17e2470f12693092b00dc2243646b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_authentication.py @@ -0,0 +1,249 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See LICENSE.txt in the project root for +# license information. +# ------------------------------------------------------------------------- +import time +from typing import TYPE_CHECKING, Optional, TypeVar, MutableMapping, Any +from azure.core.pipeline import PipelineRequest, PipelineResponse +from azure.core.pipeline.transport import HttpResponse as LegacyHttpResponse, HttpRequest as LegacyHttpRequest +from azure.core.rest import HttpResponse, HttpRequest +from . import HTTPPolicy, SansIOHTTPPolicy +from ...exceptions import ServiceRequestError + +if TYPE_CHECKING: + # pylint:disable=unused-import + from azure.core.credentials import ( + AccessToken, + TokenCredential, + AzureKeyCredential, + AzureSasCredential, + ) + +HTTPResponseType = TypeVar("HTTPResponseType", HttpResponse, LegacyHttpResponse) +HTTPRequestType = TypeVar("HTTPRequestType", HttpRequest, LegacyHttpRequest) + + +# pylint:disable=too-few-public-methods +class _BearerTokenCredentialPolicyBase: + """Base class for a Bearer Token Credential Policy. + + :param credential: The credential. + :type credential: ~azure.core.credentials.TokenCredential + :param str scopes: Lets you specify the type of access needed. + :keyword bool enable_cae: Indicates whether to enable Continuous Access Evaluation (CAE) on all requested + tokens. Defaults to False. + """ + + def __init__(self, credential: "TokenCredential", *scopes: str, **kwargs: Any) -> None: + super(_BearerTokenCredentialPolicyBase, self).__init__() + self._scopes = scopes + self._credential = credential + self._token: Optional["AccessToken"] = None + self._enable_cae: bool = kwargs.get("enable_cae", False) + + @staticmethod + def _enforce_https(request: PipelineRequest[HTTPRequestType]) -> None: + # move 'enforce_https' from options to context so it persists + # across retries but isn't passed to a transport implementation + option = request.context.options.pop("enforce_https", None) + + # True is the default setting; we needn't preserve an explicit opt in to the default behavior + if option is False: + request.context["enforce_https"] = option + + enforce_https = request.context.get("enforce_https", True) + if enforce_https and not request.http_request.url.lower().startswith("https"): + raise ServiceRequestError( + "Bearer token authentication is not permitted for non-TLS protected (non-https) URLs." + ) + + @staticmethod + def _update_headers(headers: MutableMapping[str, str], token: str) -> None: + """Updates the Authorization header with the bearer token. + + :param MutableMapping[str, str] headers: The HTTP Request headers + :param str token: The OAuth token. + """ + headers["Authorization"] = "Bearer {}".format(token) + + @property + def _need_new_token(self) -> bool: + return not self._token or self._token.expires_on - time.time() < 300 + + +class BearerTokenCredentialPolicy(_BearerTokenCredentialPolicyBase, HTTPPolicy[HTTPRequestType, HTTPResponseType]): + """Adds a bearer token Authorization header to requests. + + :param credential: The credential. + :type credential: ~azure.core.TokenCredential + :param str scopes: Lets you specify the type of access needed. + :keyword bool enable_cae: Indicates whether to enable Continuous Access Evaluation (CAE) on all requested + tokens. Defaults to False. + :raises: :class:`~azure.core.exceptions.ServiceRequestError` + """ + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Called before the policy sends a request. + + The base implementation authorizes the request with a bearer token. + + :param ~azure.core.pipeline.PipelineRequest request: the request + """ + self._enforce_https(request) + + if self._token is None or self._need_new_token: + if self._enable_cae: + self._token = self._credential.get_token(*self._scopes, enable_cae=self._enable_cae) + else: + self._token = self._credential.get_token(*self._scopes) + self._update_headers(request.http_request.headers, self._token.token) + + def authorize_request(self, request: PipelineRequest[HTTPRequestType], *scopes: str, **kwargs: Any) -> None: + """Acquire a token from the credential and authorize the request with it. + + Keyword arguments are passed to the credential's get_token method. The token will be cached and used to + authorize future requests. + + :param ~azure.core.pipeline.PipelineRequest request: the request + :param str scopes: required scopes of authentication + """ + if self._enable_cae: + kwargs.setdefault("enable_cae", self._enable_cae) + self._token = self._credential.get_token(*scopes, **kwargs) + self._update_headers(request.http_request.headers, self._token.token) + + def send(self, request: PipelineRequest[HTTPRequestType]) -> PipelineResponse[HTTPRequestType, HTTPResponseType]: + """Authorize request with a bearer token and send it to the next policy + + :param request: The pipeline request object + :type request: ~azure.core.pipeline.PipelineRequest + :return: The pipeline response object + :rtype: ~azure.core.pipeline.PipelineResponse + """ + self.on_request(request) + try: + response = self.next.send(request) + self.on_response(request, response) + except Exception: # pylint:disable=broad-except + self.on_exception(request) + raise + else: + if response.http_response.status_code == 401: + self._token = None # any cached token is invalid + if "WWW-Authenticate" in response.http_response.headers: + request_authorized = self.on_challenge(request, response) + if request_authorized: + # if we receive a challenge response, we retrieve a new token + # which matches the new target. In this case, we don't want to remove + # token from the request so clear the 'insecure_domain_change' tag + request.context.options.pop("insecure_domain_change", False) + try: + response = self.next.send(request) + self.on_response(request, response) + except Exception: # pylint:disable=broad-except + self.on_exception(request) + raise + + return response + + def on_challenge( + self, request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType] + ) -> bool: + """Authorize request according to an authentication challenge + + This method is called when the resource provider responds 401 with a WWW-Authenticate header. + + :param ~azure.core.pipeline.PipelineRequest request: the request which elicited an authentication challenge + :param ~azure.core.pipeline.PipelineResponse response: the resource provider's response + :returns: a bool indicating whether the policy should send the request + :rtype: bool + """ + # pylint:disable=unused-argument + return False + + def on_response( + self, request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType] + ) -> None: + """Executed after the request comes back from the next policy. + + :param request: Request to be modified after returning from the policy. + :type request: ~azure.core.pipeline.PipelineRequest + :param response: Pipeline response object + :type response: ~azure.core.pipeline.PipelineResponse + """ + + def on_exception(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Executed when an exception is raised while executing the next policy. + + This method is executed inside the exception handler. + + :param request: The Pipeline request object + :type request: ~azure.core.pipeline.PipelineRequest + """ + # pylint: disable=unused-argument + return + + +class AzureKeyCredentialPolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]): + """Adds a key header for the provided credential. + + :param credential: The credential used to authenticate requests. + :type credential: ~azure.core.credentials.AzureKeyCredential + :param str name: The name of the key header used for the credential. + :keyword str prefix: The name of the prefix for the header value if any. + :raises: ValueError or TypeError + """ + + def __init__( # pylint: disable=unused-argument + self, + credential: "AzureKeyCredential", + name: str, + *, + prefix: Optional[str] = None, + **kwargs: Any, + ) -> None: + super().__init__() + if not hasattr(credential, "key"): + raise TypeError("String is not a supported credential input type. Use an instance of AzureKeyCredential.") + if not name: + raise ValueError("name can not be None or empty") + if not isinstance(name, str): + raise TypeError("name must be a string.") + self._credential = credential + self._name = name + self._prefix = prefix + " " if prefix else "" + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + request.http_request.headers[self._name] = f"{self._prefix}{self._credential.key}" + + +class AzureSasCredentialPolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]): + """Adds a shared access signature to query for the provided credential. + + :param credential: The credential used to authenticate requests. + :type credential: ~azure.core.credentials.AzureSasCredential + :raises: ValueError or TypeError + """ + + def __init__(self, credential: "AzureSasCredential", **kwargs: Any) -> None: # pylint: disable=unused-argument + super(AzureSasCredentialPolicy, self).__init__() + if not credential: + raise ValueError("credential can not be None") + self._credential = credential + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + url = request.http_request.url + query = request.http_request.query + signature = self._credential.signature + if signature.startswith("?"): + signature = signature[1:] + if query: + if signature not in url: + url = url + "&" + signature + else: + if url.endswith("?"): + url = url + signature + else: + url = url + "?" + signature + request.http_request.url = url diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_authentication_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_authentication_async.py new file mode 100644 index 0000000000000000000000000000000000000000..e0f934f1a52d6303fa7e5e438f70de3f362eb408 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_authentication_async.py @@ -0,0 +1,168 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See LICENSE.txt in the project root for +# license information. +# ------------------------------------------------------------------------- +import time +from typing import TYPE_CHECKING, Any, Awaitable, Optional, cast, TypeVar + +from azure.core.credentials import AccessToken +from azure.core.pipeline import PipelineRequest, PipelineResponse +from azure.core.pipeline.policies import AsyncHTTPPolicy +from azure.core.pipeline.policies._authentication import ( + _BearerTokenCredentialPolicyBase, +) +from azure.core.pipeline.transport import AsyncHttpResponse as LegacyAsyncHttpResponse, HttpRequest as LegacyHttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.utils._utils import get_running_async_lock + +from .._tools_async import await_result + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + +AsyncHTTPResponseType = TypeVar("AsyncHTTPResponseType", AsyncHttpResponse, LegacyAsyncHttpResponse) +HTTPRequestType = TypeVar("HTTPRequestType", HttpRequest, LegacyHttpRequest) + + +class AsyncBearerTokenCredentialPolicy(AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]): + """Adds a bearer token Authorization header to requests. + + :param credential: The credential. + :type credential: ~azure.core.credentials.TokenCredential + :param str scopes: Lets you specify the type of access needed. + :keyword bool enable_cae: Indicates whether to enable Continuous Access Evaluation (CAE) on all requested + tokens. Defaults to False. + """ + + def __init__(self, credential: "AsyncTokenCredential", *scopes: str, **kwargs: Any) -> None: + super().__init__() + self._credential = credential + self._scopes = scopes + self._lock_instance = None + self._token: Optional["AccessToken"] = None + self._enable_cae: bool = kwargs.get("enable_cae", False) + + @property + def _lock(self): + if self._lock_instance is None: + self._lock_instance = get_running_async_lock() + return self._lock_instance + + async def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Adds a bearer token Authorization header to request and sends request to next policy. + + :param request: The pipeline request object to be modified. + :type request: ~azure.core.pipeline.PipelineRequest + :raises: :class:`~azure.core.exceptions.ServiceRequestError` + """ + _BearerTokenCredentialPolicyBase._enforce_https(request) # pylint:disable=protected-access + + if self._token is None or self._need_new_token(): + async with self._lock: + # double check because another coroutine may have acquired a token while we waited to acquire the lock + if self._token is None or self._need_new_token(): + if self._enable_cae: + self._token = await await_result( + self._credential.get_token, *self._scopes, enable_cae=self._enable_cae + ) + else: + self._token = await await_result(self._credential.get_token, *self._scopes) + request.http_request.headers["Authorization"] = "Bearer " + cast(AccessToken, self._token).token + + async def authorize_request(self, request: PipelineRequest[HTTPRequestType], *scopes: str, **kwargs: Any) -> None: + """Acquire a token from the credential and authorize the request with it. + + Keyword arguments are passed to the credential's get_token method. The token will be cached and used to + authorize future requests. + + :param ~azure.core.pipeline.PipelineRequest request: the request + :param str scopes: required scopes of authentication + """ + if self._enable_cae: + kwargs.setdefault("enable_cae", self._enable_cae) + async with self._lock: + self._token = await await_result(self._credential.get_token, *scopes, **kwargs) + request.http_request.headers["Authorization"] = "Bearer " + cast(AccessToken, self._token).token + + async def send( + self, request: PipelineRequest[HTTPRequestType] + ) -> PipelineResponse[HTTPRequestType, AsyncHTTPResponseType]: + """Authorize request with a bearer token and send it to the next policy + + :param request: The pipeline request object + :type request: ~azure.core.pipeline.PipelineRequest + :return: The pipeline response object + :rtype: ~azure.core.pipeline.PipelineResponse + """ + await await_result(self.on_request, request) + try: + response = await self.next.send(request) + except Exception: # pylint:disable=broad-except + await await_result(self.on_exception, request) + raise + else: + await await_result(self.on_response, request, response) + + if response.http_response.status_code == 401: + self._token = None # any cached token is invalid + if "WWW-Authenticate" in response.http_response.headers: + request_authorized = await self.on_challenge(request, response) + if request_authorized: + # if we receive a challenge response, we retrieve a new token + # which matches the new target. In this case, we don't want to remove + # token from the request so clear the 'insecure_domain_change' tag + request.context.options.pop("insecure_domain_change", False) + try: + response = await self.next.send(request) + except Exception: # pylint:disable=broad-except + await await_result(self.on_exception, request) + raise + else: + await await_result(self.on_response, request, response) + + return response + + async def on_challenge( + self, + request: PipelineRequest[HTTPRequestType], + response: PipelineResponse[HTTPRequestType, AsyncHTTPResponseType], + ) -> bool: + """Authorize request according to an authentication challenge + + This method is called when the resource provider responds 401 with a WWW-Authenticate header. + + :param ~azure.core.pipeline.PipelineRequest request: the request which elicited an authentication challenge + :param ~azure.core.pipeline.PipelineResponse response: the resource provider's response + :returns: a bool indicating whether the policy should send the request + :rtype: bool + """ + # pylint:disable=unused-argument + return False + + def on_response( + self, + request: PipelineRequest[HTTPRequestType], + response: PipelineResponse[HTTPRequestType, AsyncHTTPResponseType], + ) -> Optional[Awaitable[None]]: + """Executed after the request comes back from the next policy. + + :param request: Request to be modified after returning from the policy. + :type request: ~azure.core.pipeline.PipelineRequest + :param response: Pipeline response object + :type response: ~azure.core.pipeline.PipelineResponse + """ + + def on_exception(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Executed when an exception is raised while executing the next policy. + + This method is executed inside the exception handler. + + :param request: The Pipeline request object + :type request: ~azure.core.pipeline.PipelineRequest + """ + # pylint: disable=unused-argument + return + + def _need_new_token(self) -> bool: + return not self._token or self._token.expires_on - time.time() < 300 diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..fce407a081df8fc71de17842b43fbbdcd13150aa --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_base.py @@ -0,0 +1,140 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +import abc +import copy +import logging + +from typing import ( + Generic, + TypeVar, + Union, + Any, + Optional, + Awaitable, + Dict, +) + +from azure.core.pipeline import PipelineRequest, PipelineResponse + +HTTPResponseType = TypeVar("HTTPResponseType") +HTTPRequestType = TypeVar("HTTPRequestType") + +_LOGGER = logging.getLogger(__name__) + + +class HTTPPolicy(abc.ABC, Generic[HTTPRequestType, HTTPResponseType]): + """An HTTP policy ABC. + + Use with a synchronous pipeline. + """ + + next: "HTTPPolicy[HTTPRequestType, HTTPResponseType]" + """Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.""" + + @abc.abstractmethod + def send(self, request: PipelineRequest[HTTPRequestType]) -> PipelineResponse[HTTPRequestType, HTTPResponseType]: + """Abstract send method for a synchronous pipeline. Mutates the request. + + Context content is dependent on the HttpTransport. + + :param request: The pipeline request object + :type request: ~azure.core.pipeline.PipelineRequest + :return: The pipeline response object. + :rtype: ~azure.core.pipeline.PipelineResponse + """ + + +class SansIOHTTPPolicy(Generic[HTTPRequestType, HTTPResponseType]): + """Represents a sans I/O policy. + + SansIOHTTPPolicy is a base class for policies that only modify or + mutate a request based on the HTTP specification, and do not depend + on the specifics of any particular transport. SansIOHTTPPolicy + subclasses will function in either a Pipeline or an AsyncPipeline, + and can act either before the request is done, or after. + You can optionally make these methods coroutines (or return awaitable objects) + but they will then be tied to AsyncPipeline usage. + """ + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> Union[None, Awaitable[None]]: + """Is executed before sending the request from next policy. + + :param request: Request to be modified before sent from next policy. + :type request: ~azure.core.pipeline.PipelineRequest + """ + + def on_response( + self, + request: PipelineRequest[HTTPRequestType], + response: PipelineResponse[HTTPRequestType, HTTPResponseType], + ) -> Union[None, Awaitable[None]]: + """Is executed after the request comes back from the policy. + + :param request: Request to be modified after returning from the policy. + :type request: ~azure.core.pipeline.PipelineRequest + :param response: Pipeline response object + :type response: ~azure.core.pipeline.PipelineResponse + """ + + def on_exception( + self, + request: PipelineRequest[HTTPRequestType], # pylint: disable=unused-argument + ) -> None: + """Is executed if an exception is raised while executing the next policy. + + This method is executed inside the exception handler. + + :param request: The Pipeline request object + :type request: ~azure.core.pipeline.PipelineRequest + """ + return + + +class RequestHistory(Generic[HTTPRequestType, HTTPResponseType]): + """A container for an attempted request and the applicable response. + + This is used to document requests/responses that resulted in redirected/retried requests. + + :param http_request: The request. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :param http_response: The HTTP response. + :type http_response: ~azure.core.pipeline.transport.HttpResponse + :param Exception error: An error encountered during the request, or None if the response was received successfully. + :param dict context: The pipeline context. + """ + + def __init__( + self, + http_request: HTTPRequestType, + http_response: Optional[HTTPResponseType] = None, + error: Optional[Exception] = None, + context: Optional[Dict[str, Any]] = None, + ) -> None: + self.http_request: HTTPRequestType = copy.deepcopy(http_request) + self.http_response: Optional[HTTPResponseType] = http_response + self.error: Optional[Exception] = error + self.context: Optional[Dict[str, Any]] = context diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_base_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_base_async.py new file mode 100644 index 0000000000000000000000000000000000000000..eb0a866a7d2507d422f25723d76c6be429c5f46a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_base_async.py @@ -0,0 +1,57 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import abc + +from typing import Generic, TypeVar +from .. import PipelineRequest, PipelineResponse + +AsyncHTTPResponseType = TypeVar("AsyncHTTPResponseType") +HTTPResponseType = TypeVar("HTTPResponseType") +HTTPRequestType = TypeVar("HTTPRequestType") + + +class AsyncHTTPPolicy(abc.ABC, Generic[HTTPRequestType, AsyncHTTPResponseType]): + """An async HTTP policy ABC. + + Use with an asynchronous pipeline. + """ + + next: "AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]" + """Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.""" + + @abc.abstractmethod + async def send( + self, request: PipelineRequest[HTTPRequestType] + ) -> PipelineResponse[HTTPRequestType, AsyncHTTPResponseType]: + """Abstract send method for a asynchronous pipeline. Mutates the request. + + Context content is dependent on the HttpTransport. + + :param request: The pipeline request object. + :type request: ~azure.core.pipeline.PipelineRequest + :return: The pipeline response object. + :rtype: ~azure.core.pipeline.PipelineResponse + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_custom_hook.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_custom_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..5ee1ac5b38777e4f559208219b98f017ec360fb3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_custom_hook.py @@ -0,0 +1,79 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from typing import TypeVar, Any +from azure.core.pipeline import PipelineRequest, PipelineResponse +from azure.core.pipeline.transport import HttpResponse as LegacyHttpResponse, HttpRequest as LegacyHttpRequest +from azure.core.rest import HttpResponse, HttpRequest +from ._base import SansIOHTTPPolicy + +HTTPResponseType = TypeVar("HTTPResponseType", HttpResponse, LegacyHttpResponse) +HTTPRequestType = TypeVar("HTTPRequestType", HttpRequest, LegacyHttpRequest) + + +class CustomHookPolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]): + """A simple policy that enable the given callback + with the response. + + :keyword callback raw_request_hook: Callback function. Will be invoked on request. + :keyword callback raw_response_hook: Callback function. Will be invoked on response. + """ + + def __init__(self, **kwargs: Any): # pylint: disable=unused-argument,super-init-not-called + self._request_callback = kwargs.get("raw_request_hook") + self._response_callback = kwargs.get("raw_response_hook") + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """This is executed before sending the request to the next policy. + + :param request: The PipelineRequest object. + :type request: ~azure.core.pipeline.PipelineRequest + """ + request_callback = request.context.options.pop("raw_request_hook", None) + if request_callback: + request.context["raw_request_hook"] = request_callback + request_callback(request) + elif self._request_callback: + self._request_callback(request) + + response_callback = request.context.options.pop("raw_response_hook", None) + if response_callback: + request.context["raw_response_hook"] = response_callback + + def on_response( + self, request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType] + ) -> None: + """This is executed after the request comes back from the policy. + + :param request: The PipelineRequest object. + :type request: ~azure.core.pipeline.PipelineRequest + :param response: The PipelineResponse object. + :type response: ~azure.core.pipeline.PipelineResponse + """ + response_callback = response.context.get("raw_response_hook") + if response_callback: + response_callback(response) + elif self._response_callback: + self._response_callback(response) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_distributed_tracing.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_distributed_tracing.py new file mode 100644 index 0000000000000000000000000000000000000000..6a7619eb1cbf405ab694f8a9da9781e84e4b75b2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_distributed_tracing.py @@ -0,0 +1,144 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# -------------------------------------------------------------------------- +"""Traces network calls using the implementation library from the settings.""" +import logging +import sys +import urllib.parse +from typing import TYPE_CHECKING, Optional, Tuple, TypeVar, Union, Any, Type +from types import TracebackType + +from azure.core.pipeline import PipelineRequest, PipelineResponse +from azure.core.pipeline.policies import SansIOHTTPPolicy +from azure.core.pipeline.transport import HttpResponse as LegacyHttpResponse, HttpRequest as LegacyHttpRequest +from azure.core.rest import HttpResponse, HttpRequest +from azure.core.settings import settings +from azure.core.tracing import SpanKind + +if TYPE_CHECKING: + from azure.core.tracing._abstract_span import ( + AbstractSpan, + ) + +HTTPResponseType = TypeVar("HTTPResponseType", HttpResponse, LegacyHttpResponse) +HTTPRequestType = TypeVar("HTTPRequestType", HttpRequest, LegacyHttpRequest) +ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] +OptExcInfo = Union[ExcInfo, Tuple[None, None, None]] + +_LOGGER = logging.getLogger(__name__) + + +def _default_network_span_namer(http_request: HTTPRequestType) -> str: + """Extract the path to be used as network span name. + + :param http_request: The HTTP request + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :returns: The string to use as network span name + :rtype: str + """ + path = urllib.parse.urlparse(http_request.url).path + if not path: + path = "/" + return path + + +class DistributedTracingPolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]): + """The policy to create spans for Azure calls. + + :keyword network_span_namer: A callable to customize the span name + :type network_span_namer: callable[[~azure.core.pipeline.transport.HttpRequest], str] + :keyword tracing_attributes: Attributes to set on all created spans + :type tracing_attributes: dict[str, str] + """ + + TRACING_CONTEXT = "TRACING_CONTEXT" + _REQUEST_ID = "x-ms-client-request-id" + _RESPONSE_ID = "x-ms-request-id" + + def __init__(self, **kwargs: Any): + self._network_span_namer = kwargs.get("network_span_namer", _default_network_span_namer) + self._tracing_attributes = kwargs.get("tracing_attributes", {}) + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + ctxt = request.context.options + try: + span_impl_type = settings.tracing_implementation() + if span_impl_type is None: + return + + namer = ctxt.pop("network_span_namer", self._network_span_namer) + span_name = namer(request.http_request) + + span = span_impl_type(name=span_name, kind=SpanKind.CLIENT) + for attr, value in self._tracing_attributes.items(): + span.add_attribute(attr, value) + span.start() + + headers = span.to_header() + request.http_request.headers.update(headers) + + request.context[self.TRACING_CONTEXT] = span + except Exception as err: # pylint: disable=broad-except + _LOGGER.warning("Unable to start network span: %s", err) + + def end_span( + self, + request: PipelineRequest[HTTPRequestType], + response: Optional[HTTPResponseType] = None, + exc_info: Optional[OptExcInfo] = None, + ) -> None: + """Ends the span that is tracing the network and updates its status. + + :param request: The PipelineRequest object + :type request: ~azure.core.pipeline.PipelineRequest + :param response: The HttpResponse object + :type response: ~azure.core.rest.HTTPResponse or ~azure.core.pipeline.transport.HttpResponse + :param exc_info: The exception information + :type exc_info: tuple + """ + if self.TRACING_CONTEXT not in request.context: + return + + span: "AbstractSpan" = request.context[self.TRACING_CONTEXT] + http_request: Union[HttpRequest, LegacyHttpRequest] = request.http_request + if span is not None: + span.set_http_attributes(http_request, response=response) + request_id = http_request.headers.get(self._REQUEST_ID) + if request_id is not None: + span.add_attribute(self._REQUEST_ID, request_id) + if response and self._RESPONSE_ID in response.headers: + span.add_attribute(self._RESPONSE_ID, response.headers[self._RESPONSE_ID]) + if exc_info: + span.__exit__(*exc_info) + else: + span.finish() + + def on_response( + self, request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType] + ) -> None: + self.end_span(request, response=response.http_response) + + def on_exception(self, request: PipelineRequest[HTTPRequestType]) -> None: + self.end_span(request, exc_info=sys.exc_info()) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_redirect.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_redirect.py new file mode 100644 index 0000000000000000000000000000000000000000..efa744354564154e4a0beecf73dea6517d9fdbb2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_redirect.py @@ -0,0 +1,211 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +""" +This module is the requests implementation of Pipeline ABC +""" +import logging +from urllib.parse import urlparse +from typing import Optional, TypeVar, Dict, Any, Union, Type +from typing_extensions import Literal + +from azure.core.exceptions import TooManyRedirectsError +from azure.core.pipeline import PipelineResponse, PipelineRequest +from azure.core.pipeline.transport import ( + HttpResponse as LegacyHttpResponse, + HttpRequest as LegacyHttpRequest, + AsyncHttpResponse as LegacyAsyncHttpResponse, +) +from azure.core.rest import HttpResponse, HttpRequest, AsyncHttpResponse +from ._base import HTTPPolicy, RequestHistory +from ._utils import get_domain + +HTTPResponseType = TypeVar("HTTPResponseType", HttpResponse, LegacyHttpResponse) +AllHttpResponseType = TypeVar( + "AllHttpResponseType", HttpResponse, LegacyHttpResponse, AsyncHttpResponse, LegacyAsyncHttpResponse +) +HTTPRequestType = TypeVar("HTTPRequestType", HttpRequest, LegacyHttpRequest) +ClsRedirectPolicy = TypeVar("ClsRedirectPolicy", bound="RedirectPolicyBase") + +_LOGGER = logging.getLogger(__name__) + + +def domain_changed(original_domain: Optional[str], url: str) -> bool: + """Checks if the domain has changed. + :param str original_domain: The original domain. + :param str url: The new url. + :rtype: bool + :return: Whether the domain has changed. + """ + domain = get_domain(url) + if not original_domain: + return False + if original_domain == domain: + return False + return True + + +class RedirectPolicyBase: + + REDIRECT_STATUSES = frozenset([300, 301, 302, 303, 307, 308]) + + REDIRECT_HEADERS_BLACKLIST = frozenset(["Authorization"]) + + def __init__(self, **kwargs: Any) -> None: + self.allow: bool = kwargs.get("permit_redirects", True) + self.max_redirects: int = kwargs.get("redirect_max", 30) + + remove_headers = set(kwargs.get("redirect_remove_headers", [])) + self._remove_headers_on_redirect = remove_headers.union(self.REDIRECT_HEADERS_BLACKLIST) + redirect_status = set(kwargs.get("redirect_on_status_codes", [])) + self._redirect_on_status_codes = redirect_status.union(self.REDIRECT_STATUSES) + super(RedirectPolicyBase, self).__init__() + + @classmethod + def no_redirects(cls: Type[ClsRedirectPolicy]) -> ClsRedirectPolicy: + """Disable redirects. + + :return: A redirect policy with redirects disabled. + :rtype: ~azure.core.pipeline.policies.RedirectPolicy or ~azure.core.pipeline.policies.AsyncRedirectPolicy + """ + return cls(permit_redirects=False) + + def configure_redirects(self, options: Dict[str, Any]) -> Dict[str, Any]: + """Configures the redirect settings. + + :param options: Keyword arguments from context. + :type options: dict + :return: A dict containing redirect settings and a history of redirects. + :rtype: dict + """ + return { + "allow": options.pop("permit_redirects", self.allow), + "redirects": options.pop("redirect_max", self.max_redirects), + "history": [], + } + + def get_redirect_location( + self, response: PipelineResponse[Any, AllHttpResponseType] + ) -> Union[str, None, Literal[False]]: + """Checks for redirect status code and gets redirect location. + + :param response: The PipelineResponse object + :type response: ~azure.core.pipeline.PipelineResponse + :return: Truthy redirect location string if we got a redirect status + code and valid location. ``None`` if redirect status and no + location. ``False`` if not a redirect status code. + :rtype: str or bool or None + """ + if response.http_response.status_code in [301, 302]: + if response.http_request.method in [ + "GET", + "HEAD", + ]: + return response.http_response.headers.get("location") + return False + if response.http_response.status_code in self._redirect_on_status_codes: + return response.http_response.headers.get("location") + + return False + + def increment( + self, settings: Dict[str, Any], response: PipelineResponse[Any, AllHttpResponseType], redirect_location: str + ) -> bool: + """Increment the redirect attempts for this request. + + :param dict settings: The redirect settings + :param response: A pipeline response object. + :type response: ~azure.core.pipeline.PipelineResponse + :param str redirect_location: The redirected endpoint. + :return: Whether further redirect attempts are remaining. + False if exhausted; True if more redirect attempts available. + :rtype: bool + """ + # TODO: Revise some of the logic here. + settings["redirects"] -= 1 + settings["history"].append(RequestHistory(response.http_request, http_response=response.http_response)) + + redirected = urlparse(redirect_location) + if not redirected.netloc: + base_url = urlparse(response.http_request.url) + response.http_request.url = "{}://{}/{}".format( + base_url.scheme, base_url.netloc, redirect_location.lstrip("/") + ) + else: + response.http_request.url = redirect_location + if response.http_response.status_code == 303: + response.http_request.method = "GET" + for non_redirect_header in self._remove_headers_on_redirect: + response.http_request.headers.pop(non_redirect_header, None) + return settings["redirects"] >= 0 + + +class RedirectPolicy(RedirectPolicyBase, HTTPPolicy[HTTPRequestType, HTTPResponseType]): + """A redirect policy. + + A redirect policy in the pipeline can be configured directly or per operation. + + :keyword bool permit_redirects: Whether the client allows redirects. Defaults to True. + :keyword int redirect_max: The maximum allowed redirects. Defaults to 30. + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_sync.py + :start-after: [START redirect_policy] + :end-before: [END redirect_policy] + :language: python + :dedent: 4 + :caption: Configuring a redirect policy. + """ + + def send(self, request: PipelineRequest[HTTPRequestType]) -> PipelineResponse[HTTPRequestType, HTTPResponseType]: + """Sends the PipelineRequest object to the next policy. + Uses redirect settings to send request to redirect endpoint if necessary. + + :param request: The PipelineRequest object + :type request: ~azure.core.pipeline.PipelineRequest + :return: Returns the PipelineResponse or raises error if maximum redirects exceeded. + :rtype: ~azure.core.pipeline.PipelineResponse + :raises: ~azure.core.exceptions.TooManyRedirectsError if maximum redirects exceeded. + """ + retryable: bool = True + redirect_settings = self.configure_redirects(request.context.options) + original_domain = get_domain(request.http_request.url) if redirect_settings["allow"] else None + while retryable: + response = self.next.send(request) + redirect_location = self.get_redirect_location(response) + if redirect_location and redirect_settings["allow"]: + retryable = self.increment(redirect_settings, response, redirect_location) + request.http_request = response.http_request + if domain_changed(original_domain, request.http_request.url): + # "insecure_domain_change" is used to indicate that a redirect + # has occurred to a different domain. This tells the SensitiveHeaderCleanupPolicy + # to clean up sensitive headers. We need to remove it before sending the request + # to the transport layer. + request.context.options["insecure_domain_change"] = True + continue + return response + + raise TooManyRedirectsError(redirect_settings["history"]) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_redirect_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_redirect_async.py new file mode 100644 index 0000000000000000000000000000000000000000..82a79bec253f99de29196b9dfabbbabf88415e3b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_redirect_async.py @@ -0,0 +1,87 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from typing import TypeVar +from azure.core.exceptions import TooManyRedirectsError +from azure.core.pipeline import PipelineResponse, PipelineRequest +from azure.core.pipeline.transport import AsyncHttpResponse as LegacyAsyncHttpResponse, HttpRequest as LegacyHttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest +from . import AsyncHTTPPolicy +from ._redirect import RedirectPolicyBase, domain_changed +from ._utils import get_domain + +AsyncHTTPResponseType = TypeVar("AsyncHTTPResponseType", AsyncHttpResponse, LegacyAsyncHttpResponse) +HTTPRequestType = TypeVar("HTTPRequestType", HttpRequest, LegacyHttpRequest) + + +class AsyncRedirectPolicy(RedirectPolicyBase, AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]): + """An async redirect policy. + + An async redirect policy in the pipeline can be configured directly or per operation. + + :keyword bool permit_redirects: Whether the client allows redirects. Defaults to True. + :keyword int redirect_max: The maximum allowed redirects. Defaults to 30. + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_async.py + :start-after: [START async_redirect_policy] + :end-before: [END async_redirect_policy] + :language: python + :dedent: 4 + :caption: Configuring an async redirect policy. + """ + + async def send( + self, request: PipelineRequest[HTTPRequestType] + ) -> PipelineResponse[HTTPRequestType, AsyncHTTPResponseType]: + """Sends the PipelineRequest object to the next policy. + Uses redirect settings to send the request to redirect endpoint if necessary. + + :param request: The PipelineRequest object + :type request: ~azure.core.pipeline.PipelineRequest + :return: Returns the PipelineResponse or raises error if maximum redirects exceeded. + :rtype: ~azure.core.pipeline.PipelineResponse + :raises: ~azure.core.exceptions.TooManyRedirectsError if maximum redirects exceeded. + """ + redirects_remaining = True + redirect_settings = self.configure_redirects(request.context.options) + original_domain = get_domain(request.http_request.url) if redirect_settings["allow"] else None + while redirects_remaining: + response = await self.next.send(request) + redirect_location = self.get_redirect_location(response) + if redirect_location and redirect_settings["allow"]: + redirects_remaining = self.increment(redirect_settings, response, redirect_location) + request.http_request = response.http_request + if domain_changed(original_domain, request.http_request.url): + # "insecure_domain_change" is used to indicate that a redirect + # has occurred to a different domain. This tells the SensitiveHeaderCleanupPolicy + # to clean up sensitive headers. We need to remove it before sending the request + # to the transport layer. + request.context.options["insecure_domain_change"] = True + continue + return response + + raise TooManyRedirectsError(redirect_settings["history"]) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_retry.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_retry.py new file mode 100644 index 0000000000000000000000000000000000000000..12e2a19858944812b164b04fb5f4b2535eddab35 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_retry.py @@ -0,0 +1,562 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from typing import TypeVar, Any, Dict, Optional, Type, List, Union, cast, IO +from io import SEEK_SET, UnsupportedOperation +import logging +import time +from enum import Enum +from azure.core.configuration import ConnectionConfiguration +from azure.core.pipeline import PipelineResponse, PipelineRequest, PipelineContext +from azure.core.pipeline.transport import ( + HttpResponse as LegacyHttpResponse, + AsyncHttpResponse as LegacyAsyncHttpResponse, + HttpRequest as LegacyHttpRequest, + HttpTransport, +) +from azure.core.rest import HttpResponse, AsyncHttpResponse, HttpRequest +from azure.core.exceptions import ( + AzureError, + ClientAuthenticationError, + ServiceResponseError, + ServiceRequestError, + ServiceRequestTimeoutError, + ServiceResponseTimeoutError, +) + +from ._base import HTTPPolicy, RequestHistory +from . import _utils +from ..._enum_meta import CaseInsensitiveEnumMeta + +HTTPResponseType = TypeVar("HTTPResponseType", HttpResponse, LegacyHttpResponse) +AllHttpResponseType = TypeVar( + "AllHttpResponseType", HttpResponse, LegacyHttpResponse, AsyncHttpResponse, LegacyAsyncHttpResponse +) +HTTPRequestType = TypeVar("HTTPRequestType", HttpRequest, LegacyHttpRequest) +ClsRetryPolicy = TypeVar("ClsRetryPolicy", bound="RetryPolicyBase") + +_LOGGER = logging.getLogger(__name__) + + +class RetryMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + # pylint: disable=enum-must-be-uppercase + Exponential = "exponential" + Fixed = "fixed" + + +class RetryPolicyBase: + # pylint: disable=too-many-instance-attributes + #: Maximum backoff time. + BACKOFF_MAX = 120 + _SAFE_CODES = set(range(506)) - set([408, 429, 500, 502, 503, 504]) + _RETRY_CODES = set(range(999)) - _SAFE_CODES + + def __init__(self, **kwargs: Any) -> None: + self.total_retries: int = kwargs.pop("retry_total", 10) + self.connect_retries: int = kwargs.pop("retry_connect", 3) + self.read_retries: int = kwargs.pop("retry_read", 3) + self.status_retries: int = kwargs.pop("retry_status", 3) + self.backoff_factor: float = kwargs.pop("retry_backoff_factor", 0.8) + self.backoff_max: int = kwargs.pop("retry_backoff_max", self.BACKOFF_MAX) + self.retry_mode: RetryMode = kwargs.pop("retry_mode", RetryMode.Exponential) + self.timeout: int = kwargs.pop("timeout", 604800) + + retry_codes = self._RETRY_CODES + status_codes = kwargs.pop("retry_on_status_codes", []) + self._retry_on_status_codes = set(status_codes) | retry_codes + self._method_whitelist = frozenset(["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"]) + self._respect_retry_after_header = True + super(RetryPolicyBase, self).__init__() + + @classmethod + def no_retries(cls: Type[ClsRetryPolicy]) -> ClsRetryPolicy: + """Disable retries. + + :return: A retry policy with retries disabled. + :rtype: ~azure.core.pipeline.policies.RetryPolicy or ~azure.core.pipeline.policies.AsyncRetryPolicy + """ + return cls(retry_total=0) + + def configure_retries(self, options: Dict[str, Any]) -> Dict[str, Any]: + """Configures the retry settings. + + :param options: keyword arguments from context. + :type options: dict + :return: A dict containing settings and history for retries. + :rtype: dict + """ + return { + "total": options.pop("retry_total", self.total_retries), + "connect": options.pop("retry_connect", self.connect_retries), + "read": options.pop("retry_read", self.read_retries), + "status": options.pop("retry_status", self.status_retries), + "backoff": options.pop("retry_backoff_factor", self.backoff_factor), + "max_backoff": options.pop("retry_backoff_max", self.BACKOFF_MAX), + "methods": options.pop("retry_on_methods", self._method_whitelist), + "timeout": options.pop("timeout", self.timeout), + "history": [], + } + + def get_backoff_time(self, settings: Dict[str, Any]) -> float: + """Returns the current backoff time. + + :param dict settings: The retry settings. + :return: The current backoff value. + :rtype: float + """ + # We want to consider only the last consecutive errors sequence (Ignore redirects). + consecutive_errors_len = len(settings["history"]) + if consecutive_errors_len <= 1: + return 0 + + if self.retry_mode == RetryMode.Fixed: + backoff_value = settings["backoff"] + else: + backoff_value = settings["backoff"] * (2 ** (consecutive_errors_len - 1)) + return min(settings["max_backoff"], backoff_value) + + def parse_retry_after(self, retry_after: str) -> float: + """Helper to parse Retry-After and get value in seconds. + + :param str retry_after: Retry-After header + :rtype: float + :return: Value of Retry-After in seconds. + """ + return _utils.parse_retry_after(retry_after) + + def get_retry_after(self, response: PipelineResponse[Any, AllHttpResponseType]) -> Optional[float]: + """Get the value of Retry-After in seconds. + + :param response: The PipelineResponse object + :type response: ~azure.core.pipeline.PipelineResponse + :return: Value of Retry-After in seconds. + :rtype: float or None + """ + return _utils.get_retry_after(response) + + def _is_connection_error(self, err: Exception) -> bool: + """Errors when we're fairly sure that the server did not receive the + request, so it should be safe to retry. + + :param err: The error raised by the pipeline. + :type err: ~azure.core.exceptions.AzureError + :return: True if connection error, False if not. + :rtype: bool + """ + return isinstance(err, ServiceRequestError) + + def _is_read_error(self, err: Exception) -> bool: + """Errors that occur after the request has been started, so we should + assume that the server began processing it. + + :param err: The error raised by the pipeline. + :type err: ~azure.core.exceptions.AzureError + :return: True if read error, False if not. + :rtype: bool + """ + return isinstance(err, ServiceResponseError) + + def _is_method_retryable( + self, + settings: Dict[str, Any], + request: HTTPRequestType, + response: Optional[AllHttpResponseType] = None, + ): + """Checks if a given HTTP method should be retried upon, depending if + it is included on the method allowlist. + + :param dict settings: The retry settings. + :param request: The HTTP request object. + :type request: ~azure.core.rest.HttpRequest + :param response: The HTTP response object. + :type response: ~azure.core.rest.HttpResponse or ~azure.core.rest.AsyncHttpResponse + :return: True if method should be retried upon. False if not in method allowlist. + :rtype: bool + """ + if response and request.method.upper() in ["POST", "PATCH"] and response.status_code in [500, 503, 504]: + return True + if request.method.upper() not in settings["methods"]: + return False + + return True + + def is_retry( + self, settings: Dict[str, Any], response: PipelineResponse[HTTPRequestType, AllHttpResponseType] + ) -> bool: + """Checks if method/status code is retryable. + + Based on allowlists and control variables such as the number of + total retries to allow, whether to respect the Retry-After header, + whether this header is present, and whether the returned status + code is on the list of status codes to be retried upon on the + presence of the aforementioned header. + + The behavior is: + - If status_code < 400: don't retry + - Else if Retry-After present: retry + - Else: retry based on the safe status code list ([408, 429, 500, 502, 503, 504]) + + + :param dict settings: The retry settings. + :param response: The PipelineResponse object + :type response: ~azure.core.pipeline.PipelineResponse + :return: True if method/status code is retryable. False if not retryable. + :rtype: bool + """ + if response.http_response.status_code < 400: + return False + has_retry_after = bool(response.http_response.headers.get("Retry-After")) + if has_retry_after and self._respect_retry_after_header: + return True + if not self._is_method_retryable(settings, response.http_request, response=response.http_response): + return False + return settings["total"] and response.http_response.status_code in self._retry_on_status_codes + + def is_exhausted(self, settings: Dict[str, Any]) -> bool: + """Checks if any retries left. + + :param dict settings: the retry settings + :return: False if have more retries. True if retries exhausted. + :rtype: bool + """ + settings_retry_count = ( + settings["total"], + settings["connect"], + settings["read"], + settings["status"], + ) + retry_counts: List[int] = list(filter(None, settings_retry_count)) + if not retry_counts: + return False + + return min(retry_counts) < 0 + + def increment( + self, + settings: Dict[str, Any], + response: Optional[ + Union[PipelineRequest[HTTPRequestType], PipelineResponse[HTTPRequestType, AllHttpResponseType]] + ] = None, + error: Optional[Exception] = None, + ) -> bool: + """Increment the retry counters. + + :param settings: The retry settings. + :type settings: dict + :param response: A pipeline response object. + :type response: ~azure.core.pipeline.PipelineResponse + :param error: An error encountered during the request, or + None if the response was received successfully. + :type error: ~azure.core.exceptions.AzureError + :return: Whether any retry attempt is available + True if more retry attempts available, False otherwise + :rtype: bool + """ + # FIXME This code is not None safe: https://github.com/Azure/azure-sdk-for-python/issues/31528 + response = cast( + Union[PipelineRequest[HTTPRequestType], PipelineResponse[HTTPRequestType, AllHttpResponseType]], response + ) + + settings["total"] -= 1 + + if isinstance(response, PipelineResponse) and response.http_response.status_code == 202: + return False + + if error and self._is_connection_error(error): + # Connect retry? + settings["connect"] -= 1 + settings["history"].append(RequestHistory(response.http_request, error=error)) + + elif error and self._is_read_error(error): + # Read retry? + settings["read"] -= 1 + if hasattr(response, "http_request"): + settings["history"].append(RequestHistory(response.http_request, error=error)) + + else: + # Incrementing because of a server error like a 500 in + # status_forcelist and the given method is in the allowlist + if response: + settings["status"] -= 1 + if hasattr(response, "http_request") and hasattr(response, "http_response"): + settings["history"].append( + RequestHistory(response.http_request, http_response=response.http_response) + ) + + if self.is_exhausted(settings): + return False + + if response.http_request.body and hasattr(response.http_request.body, "read"): + if "body_position" not in settings: + return False + try: + # attempt to rewind the body to the initial position + # If it has "read", it has "seek", so casting for mypy + cast(IO[bytes], response.http_request.body).seek(settings["body_position"], SEEK_SET) + except (UnsupportedOperation, ValueError, AttributeError): + # if body is not seekable, then retry would not work + return False + file_positions = settings.get("file_positions") + if response.http_request.files and file_positions: + try: + for value in response.http_request.files.values(): + file_name, body = value[0], value[1] + if file_name in file_positions: + position = file_positions[file_name] + body.seek(position, SEEK_SET) + except (UnsupportedOperation, ValueError, AttributeError): + # if body is not seekable, then retry would not work + return False + return True + + def update_context(self, context: PipelineContext, retry_settings: Dict[str, Any]) -> None: + """Updates retry history in pipeline context. + + :param context: The pipeline context. + :type context: ~azure.core.pipeline.PipelineContext + :param retry_settings: The retry settings. + :type retry_settings: dict + """ + if retry_settings["history"]: + context["history"] = retry_settings["history"] + + def _configure_timeout( + self, request: PipelineRequest[HTTPRequestType], absolute_timeout: float, is_response_error: bool + ) -> None: + if absolute_timeout <= 0: + if is_response_error: + raise ServiceResponseTimeoutError("Response timeout") + raise ServiceRequestTimeoutError("Request timeout") + + # if connection_timeout is already set, ensure it doesn't exceed absolute_timeout + connection_timeout = request.context.options.get("connection_timeout") + if connection_timeout: + request.context.options["connection_timeout"] = min(connection_timeout, absolute_timeout) + + # otherwise, try to ensure the transport's configured connection_timeout doesn't exceed absolute_timeout + # ("connection_config" isn't defined on Async/HttpTransport but all implementations in this library have it) + elif hasattr(request.context.transport, "connection_config"): + # FIXME This is fragile, should be refactored. Casting my way for mypy + # https://github.com/Azure/azure-sdk-for-python/issues/31530 + connection_config = cast( + ConnectionConfiguration, request.context.transport.connection_config # type: ignore + ) + + default_timeout = getattr(connection_config, "timeout", absolute_timeout) + try: + if absolute_timeout < default_timeout: + request.context.options["connection_timeout"] = absolute_timeout + except TypeError: + # transport.connection_config.timeout is something unexpected (not a number) + pass + + def _configure_positions(self, request: PipelineRequest[HTTPRequestType], retry_settings: Dict[str, Any]) -> None: + body_position = None + file_positions: Optional[Dict[str, int]] = None + if request.http_request.body and hasattr(request.http_request.body, "read"): + try: + # If it has "read", it has "tell", so casting for mypy + body_position = cast(IO[bytes], request.http_request.body).tell() + except (AttributeError, UnsupportedOperation): + # if body position cannot be obtained, then retries will not work + pass + else: + if request.http_request.files: + file_positions = {} + try: + for value in request.http_request.files.values(): + name, body = value[0], value[1] + if name and body and hasattr(body, "read"): + # If it has "read", it has "tell", so casting for mypy + position = cast(IO[bytes], body).tell() + file_positions[name] = position + except (AttributeError, UnsupportedOperation): + file_positions = None + + retry_settings["body_position"] = body_position + retry_settings["file_positions"] = file_positions + + +class RetryPolicy(RetryPolicyBase, HTTPPolicy[HTTPRequestType, HTTPResponseType]): + """A retry policy. + + The retry policy in the pipeline can be configured directly, or tweaked on a per-call basis. + + :keyword int retry_total: Total number of retries to allow. Takes precedence over other counts. + Default value is 10. + + :keyword int retry_connect: How many connection-related errors to retry on. + These are errors raised before the request is sent to the remote server, + which we assume has not triggered the server to process the request. Default value is 3. + + :keyword int retry_read: How many times to retry on read errors. + These errors are raised after the request was sent to the server, so the + request may have side-effects. Default value is 3. + + :keyword int retry_status: How many times to retry on bad status codes. Default value is 3. + + :keyword float retry_backoff_factor: A backoff factor to apply between attempts after the second try + (most errors are resolved immediately by a second try without a delay). + In fixed mode, retry policy will always sleep for {backoff factor}. + In 'exponential' mode, retry policy will sleep for: `{backoff factor} * (2 ** ({number of total retries} - 1))` + seconds. If the backoff_factor is 0.1, then the retry will sleep + for [0.0s, 0.2s, 0.4s, ...] between retries. The default value is 0.8. + + :keyword int retry_backoff_max: The maximum back off time. Default value is 120 seconds (2 minutes). + + :keyword RetryMode retry_mode: Fixed or exponential delay between attemps, default is exponential. + + :keyword int timeout: Timeout setting for the operation in seconds, default is 604800s (7 days). + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_sync.py + :start-after: [START retry_policy] + :end-before: [END retry_policy] + :language: python + :dedent: 4 + :caption: Configuring a retry policy. + """ + + def _sleep_for_retry( + self, + response: PipelineResponse[HTTPRequestType, HTTPResponseType], + transport: HttpTransport[HTTPRequestType, HTTPResponseType], + ) -> bool: + """Sleep based on the Retry-After response header value. + + :param response: The PipelineResponse object. + :type response: ~azure.core.pipeline.PipelineResponse + :param transport: The HTTP transport type. + :type transport: ~azure.core.pipeline.transport.HttpTransport + :return: Whether a sleep was done or not + :rtype: bool + """ + retry_after = self.get_retry_after(response) + if retry_after: + transport.sleep(retry_after) + return True + return False + + def _sleep_backoff( + self, settings: Dict[str, Any], transport: HttpTransport[HTTPRequestType, HTTPResponseType] + ) -> None: + """Sleep using exponential backoff. Immediately returns if backoff is 0. + + :param dict settings: The retry settings. + :param transport: The HTTP transport type. + :type transport: ~azure.core.pipeline.transport.HttpTransport + """ + backoff = self.get_backoff_time(settings) + if backoff <= 0: + return + transport.sleep(backoff) + + def sleep( + self, + settings: Dict[str, Any], + transport: HttpTransport[HTTPRequestType, HTTPResponseType], + response: Optional[PipelineResponse[HTTPRequestType, HTTPResponseType]] = None, + ) -> None: + """Sleep between retry attempts. + + This method will respect a server's ``Retry-After`` response header + and sleep the duration of the time requested. If that is not present, it + will use an exponential backoff. By default, the backoff factor is 0 and + this method will return immediately. + + :param dict settings: The retry settings. + :param transport: The HTTP transport type. + :type transport: ~azure.core.pipeline.transport.HttpTransport + :param response: The PipelineResponse object. + :type response: ~azure.core.pipeline.PipelineResponse + """ + if response: + slept = self._sleep_for_retry(response, transport) + if slept: + return + self._sleep_backoff(settings, transport) + + def send(self, request: PipelineRequest[HTTPRequestType]) -> PipelineResponse[HTTPRequestType, HTTPResponseType]: + """Sends the PipelineRequest object to the next policy. Uses retry settings if necessary. + + :param request: The PipelineRequest object + :type request: ~azure.core.pipeline.PipelineRequest + :return: Returns the PipelineResponse or raises error if maximum retries exceeded. + :rtype: ~azure.core.pipeline.PipelineResponse + :raises: ~azure.core.exceptions.AzureError if maximum retries exceeded. + :raises: ~azure.core.exceptions.ClientAuthenticationError if authentication + """ + retry_active = True + response = None + retry_settings = self.configure_retries(request.context.options) + self._configure_positions(request, retry_settings) + + absolute_timeout = retry_settings["timeout"] + is_response_error = True + + while retry_active: + start_time = time.time() + # PipelineContext types transport as a Union of HttpTransport and AsyncHttpTransport, but + # here we know that this is an HttpTransport. + # The correct fix is to make PipelineContext generic, but that's a breaking change and a lot of + # generic to update in Pipeline, PipelineClient, PipelineRequest, PipelineResponse, etc. + transport: HttpTransport[HTTPRequestType, HTTPResponseType] = cast( + HttpTransport[HTTPRequestType, HTTPResponseType], request.context.transport + ) + try: + self._configure_timeout(request, absolute_timeout, is_response_error) + response = self.next.send(request) + if self.is_retry(retry_settings, response): + retry_active = self.increment(retry_settings, response=response) + if retry_active: + self.sleep(retry_settings, transport, response=response) + is_response_error = True + continue + break + except ClientAuthenticationError: # pylint:disable=try-except-raise + # the authentication policy failed such that the client's request can't + # succeed--we'll never have a response to it, so propagate the exception + raise + except AzureError as err: + if absolute_timeout > 0 and self._is_method_retryable(retry_settings, request.http_request): + retry_active = self.increment(retry_settings, response=request, error=err) + if retry_active: + self.sleep(retry_settings, transport) + if isinstance(err, ServiceRequestError): + is_response_error = False + else: + is_response_error = True + continue + raise err + finally: + end_time = time.time() + if absolute_timeout: + absolute_timeout -= end_time - start_time + if not response: + raise AzureError("Maximum retries exceeded.") + + self.update_context(response.context, retry_settings) + return response diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_retry_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_retry_async.py new file mode 100644 index 0000000000000000000000000000000000000000..1e63e3b09fe75a0aea1d4748422469472981d4d4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_retry_async.py @@ -0,0 +1,214 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +""" +This module is the requests implementation of Pipeline ABC +""" +from typing import TypeVar, Dict, Any, Optional, cast +import logging +import time +from azure.core.pipeline import PipelineRequest, PipelineResponse +from azure.core.pipeline.transport import ( + AsyncHttpResponse as LegacyAsyncHttpResponse, + HttpRequest as LegacyHttpRequest, + AsyncHttpTransport, +) +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.exceptions import ( + AzureError, + ClientAuthenticationError, + ServiceRequestError, +) +from ._base_async import AsyncHTTPPolicy +from ._retry import RetryPolicyBase + +AsyncHTTPResponseType = TypeVar("AsyncHTTPResponseType", AsyncHttpResponse, LegacyAsyncHttpResponse) +HTTPRequestType = TypeVar("HTTPRequestType", HttpRequest, LegacyHttpRequest) + +_LOGGER = logging.getLogger(__name__) + + +class AsyncRetryPolicy(RetryPolicyBase, AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]): + """Async flavor of the retry policy. + + The async retry policy in the pipeline can be configured directly, or tweaked on a per-call basis. + + :keyword int retry_total: Total number of retries to allow. Takes precedence over other counts. + Default value is 10. + + :keyword int retry_connect: How many connection-related errors to retry on. + These are errors raised before the request is sent to the remote server, + which we assume has not triggered the server to process the request. Default value is 3. + + :keyword int retry_read: How many times to retry on read errors. + These errors are raised after the request was sent to the server, so the + request may have side-effects. Default value is 3. + + :keyword int retry_status: How many times to retry on bad status codes. Default value is 3. + + :keyword float retry_backoff_factor: A backoff factor to apply between attempts after the second try + (most errors are resolved immediately by a second try without a delay). + Retry policy will sleep for: `{backoff factor} * (2 ** ({number of total retries} - 1))` + seconds. If the backoff_factor is 0.1, then the retry will sleep + for [0.0s, 0.2s, 0.4s, ...] between retries. The default value is 0.8. + + :keyword int retry_backoff_max: The maximum back off time. Default value is 120 seconds (2 minutes). + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_async.py + :start-after: [START async_retry_policy] + :end-before: [END async_retry_policy] + :language: python + :dedent: 4 + :caption: Configuring an async retry policy. + """ + + async def _sleep_for_retry( + self, + response: PipelineResponse[HTTPRequestType, AsyncHTTPResponseType], + transport: AsyncHttpTransport[HTTPRequestType, AsyncHTTPResponseType], + ) -> bool: + """Sleep based on the Retry-After response header value. + + :param response: The PipelineResponse object. + :type response: ~azure.core.pipeline.PipelineResponse + :param transport: The HTTP transport type. + :type transport: ~azure.core.pipeline.transport.AsyncHttpTransport + :return: Whether the retry-after value was found. + :rtype: bool + """ + retry_after = self.get_retry_after(response) + if retry_after: + await transport.sleep(retry_after) + return True + return False + + async def _sleep_backoff( + self, settings: Dict[str, Any], transport: AsyncHttpTransport[HTTPRequestType, AsyncHTTPResponseType] + ) -> None: + """Sleep using exponential backoff. Immediately returns if backoff is 0. + + :param dict settings: The retry settings. + :param transport: The HTTP transport type. + :type transport: ~azure.core.pipeline.transport.AsyncHttpTransport + """ + backoff = self.get_backoff_time(settings) + if backoff <= 0: + return + await transport.sleep(backoff) + + async def sleep( + self, + settings: Dict[str, Any], + transport: AsyncHttpTransport[HTTPRequestType, AsyncHTTPResponseType], + response: Optional[PipelineResponse[HTTPRequestType, AsyncHTTPResponseType]] = None, + ) -> None: + """Sleep between retry attempts. + + This method will respect a server's ``Retry-After`` response header + and sleep the duration of the time requested. If that is not present, it + will use an exponential backoff. By default, the backoff factor is 0 and + this method will return immediately. + + :param dict settings: The retry settings. + :param transport: The HTTP transport type. + :type transport: ~azure.core.pipeline.transport.AsyncHttpTransport + :param response: The PipelineResponse object. + :type response: ~azure.core.pipeline.PipelineResponse + """ + if response: + slept = await self._sleep_for_retry(response, transport) + if slept: + return + await self._sleep_backoff(settings, transport) + + async def send( + self, request: PipelineRequest[HTTPRequestType] + ) -> PipelineResponse[HTTPRequestType, AsyncHTTPResponseType]: + """Uses the configured retry policy to send the request to the next policy in the pipeline. + + :param request: The PipelineRequest object + :type request: ~azure.core.pipeline.PipelineRequest + :return: Returns the PipelineResponse or raises error if maximum retries exceeded. + :rtype: ~azure.core.pipeline.PipelineResponse + :raise: ~azure.core.exceptions.AzureError if maximum retries exceeded. + :raise: ~azure.core.exceptions.ClientAuthenticationError if authentication fails + """ + retry_active = True + response = None + retry_settings = self.configure_retries(request.context.options) + self._configure_positions(request, retry_settings) + + absolute_timeout = retry_settings["timeout"] + is_response_error = True + + while retry_active: + start_time = time.time() + # PipelineContext types transport as a Union of HttpTransport and AsyncHttpTransport, but + # here we know that this is an AsyncHttpTransport. + # The correct fix is to make PipelineContext generic, but that's a breaking change and a lot of + # generic to update in Pipeline, PipelineClient, PipelineRequest, PipelineResponse, etc. + transport: AsyncHttpTransport[HTTPRequestType, AsyncHTTPResponseType] = cast( + AsyncHttpTransport[HTTPRequestType, AsyncHTTPResponseType], request.context.transport + ) + try: + self._configure_timeout(request, absolute_timeout, is_response_error) + response = await self.next.send(request) + if self.is_retry(retry_settings, response): + retry_active = self.increment(retry_settings, response=response) + if retry_active: + await self.sleep( + retry_settings, + transport, + response=response, + ) + is_response_error = True + continue + break + except ClientAuthenticationError: # pylint:disable=try-except-raise + # the authentication policy failed such that the client's request can't + # succeed--we'll never have a response to it, so propagate the exception + raise + except AzureError as err: + if absolute_timeout > 0 and self._is_method_retryable(retry_settings, request.http_request): + retry_active = self.increment(retry_settings, response=request, error=err) + if retry_active: + await self.sleep(retry_settings, transport) + if isinstance(err, ServiceRequestError): + is_response_error = False + else: + is_response_error = True + continue + raise err + finally: + end_time = time.time() + if absolute_timeout: + absolute_timeout -= end_time - start_time + if not response: + raise AzureError("Maximum retries exceeded.") + + self.update_context(response.context, retry_settings) + return response diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_sensitive_header_cleanup_policy.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_sensitive_header_cleanup_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c883bb2bea0f58e04651e9c9236ce2ee366bee4a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_sensitive_header_cleanup_policy.py @@ -0,0 +1,77 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from typing import List, Optional, Any, TypeVar +from azure.core.pipeline import PipelineRequest +from azure.core.pipeline.transport import HttpRequest as LegacyHttpRequest, HttpResponse as LegacyHttpResponse +from azure.core.rest import HttpRequest, HttpResponse +from ._base import SansIOHTTPPolicy + +HTTPResponseType = TypeVar("HTTPResponseType", HttpResponse, LegacyHttpResponse) +HTTPRequestType = TypeVar("HTTPRequestType", HttpRequest, LegacyHttpRequest) + + +class SensitiveHeaderCleanupPolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]): + """A simple policy that cleans up sensitive headers + + :keyword list[str] blocked_redirect_headers: The headers to clean up when redirecting to another domain. + :keyword bool disable_redirect_cleanup: Opt out cleaning up sensitive headers when redirecting to another domain. + """ + + DEFAULT_SENSITIVE_HEADERS = set( + [ + "Authorization", + "x-ms-authorization-auxiliary", + ] + ) + + def __init__( + self, # pylint: disable=unused-argument + *, + blocked_redirect_headers: Optional[List[str]] = None, + disable_redirect_cleanup: bool = False, + **kwargs: Any + ) -> None: + self._disable_redirect_cleanup = disable_redirect_cleanup + self._blocked_redirect_headers = ( + SensitiveHeaderCleanupPolicy.DEFAULT_SENSITIVE_HEADERS + if blocked_redirect_headers is None + else blocked_redirect_headers + ) + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """This is executed before sending the request to the next policy. + + :param request: The PipelineRequest object. + :type request: ~azure.core.pipeline.PipelineRequest + """ + # "insecure_domain_change" is used to indicate that a redirect + # has occurred to a different domain. This tells the SensitiveHeaderCleanupPolicy + # to clean up sensitive headers. We need to remove it before sending the request + # to the transport layer. + insecure_domain_change = request.context.options.pop("insecure_domain_change", False) + if not self._disable_redirect_cleanup and insecure_domain_change: + for header in self._blocked_redirect_headers: + request.http_request.headers.pop(header, None) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_universal.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_universal.py new file mode 100644 index 0000000000000000000000000000000000000000..b7fc6bfc2cfabcf4f2c6adabc855155480667083 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_universal.py @@ -0,0 +1,751 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +""" +This module is the requests implementation of Pipeline ABC +""" +import json +import inspect +import logging +import os +import platform +import xml.etree.ElementTree as ET +import types +import re +import uuid +from typing import IO, cast, Union, Optional, AnyStr, Dict, Any, Set, MutableMapping +import urllib.parse + +from azure.core import __version__ as azcore_version +from azure.core.exceptions import DecodeError + +from azure.core.pipeline import PipelineRequest, PipelineResponse +from ._base import SansIOHTTPPolicy + +from ..transport import HttpRequest as LegacyHttpRequest +from ..transport._base import _HttpResponseBase as LegacySansIOHttpResponse +from ...rest import HttpRequest +from ...rest._rest_py3 import _HttpResponseBase as SansIOHttpResponse + +_LOGGER = logging.getLogger(__name__) + +HTTPRequestType = Union[LegacyHttpRequest, HttpRequest] +HTTPResponseType = Union[LegacySansIOHttpResponse, SansIOHttpResponse] +PipelineResponseType = PipelineResponse[HTTPRequestType, HTTPResponseType] + + +class HeadersPolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]): + """A simple policy that sends the given headers with the request. + + This will overwrite any headers already defined in the request. Headers can be + configured up front, where any custom headers will be applied to all outgoing + operations, and additional headers can also be added dynamically per operation. + + :param dict base_headers: Headers to send with the request. + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_sansio.py + :start-after: [START headers_policy] + :end-before: [END headers_policy] + :language: python + :dedent: 4 + :caption: Configuring a headers policy. + """ + + def __init__( + self, base_headers: Optional[Dict[str, str]] = None, **kwargs: Any + ) -> None: # pylint: disable=super-init-not-called + self._headers: Dict[str, str] = base_headers or {} + self._headers.update(kwargs.pop("headers", {})) + + @property + def headers(self) -> Dict[str, str]: + """The current headers collection. + + :rtype: dict[str, str] + :return: The current headers collection. + """ + return self._headers + + def add_header(self, key: str, value: str) -> None: + """Add a header to the configuration to be applied to all requests. + + :param str key: The header. + :param str value: The header's value. + """ + self._headers[key] = value + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Updates with the given headers before sending the request to the next policy. + + :param request: The PipelineRequest object + :type request: ~azure.core.pipeline.PipelineRequest + """ + request.http_request.headers.update(self.headers) + additional_headers = request.context.options.pop("headers", {}) + if additional_headers: + request.http_request.headers.update(additional_headers) + + +class _Unset: + pass + + +class RequestIdPolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]): + """A simple policy that sets the given request id in the header. + + This will overwrite request id that is already defined in the request. Request id can be + configured up front, where the request id will be applied to all outgoing + operations, and additional request id can also be set dynamically per operation. + + :keyword str request_id: The request id to be added into header. + :keyword bool auto_request_id: Auto generates a unique request ID per call if true which is by default. + :keyword str request_id_header_name: Header name to use. Default is "x-ms-client-request-id". + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_sansio.py + :start-after: [START request_id_policy] + :end-before: [END request_id_policy] + :language: python + :dedent: 4 + :caption: Configuring a request id policy. + """ + + def __init__( + self, # pylint: disable=unused-argument + *, + request_id: Union[str, Any] = _Unset, + auto_request_id: bool = True, + request_id_header_name: str = "x-ms-client-request-id", + **kwargs: Any + ) -> None: + super() + self._request_id = request_id + self._auto_request_id = auto_request_id + self._request_id_header_name = request_id_header_name + + def set_request_id(self, value: str) -> None: + """Add the request id to the configuration to be applied to all requests. + + :param str value: The request id value. + """ + self._request_id = value + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Updates with the given request id before sending the request to the next policy. + + :param request: The PipelineRequest object + :type request: ~azure.core.pipeline.PipelineRequest + """ + request_id = unset = object() + if "request_id" in request.context.options: + request_id = request.context.options.pop("request_id") + if request_id is None: + return + elif self._request_id is None: + return + elif self._request_id is not _Unset: + if self._request_id_header_name in request.http_request.headers: + return + request_id = self._request_id + elif self._auto_request_id: + if self._request_id_header_name in request.http_request.headers: + return + request_id = str(uuid.uuid1()) + if request_id is not unset: + header = {self._request_id_header_name: cast(str, request_id)} + request.http_request.headers.update(header) + + +class UserAgentPolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]): + """User-Agent Policy. Allows custom values to be added to the User-Agent header. + + :param str base_user_agent: Sets the base user agent value. + + :keyword bool user_agent_overwrite: Overwrites User-Agent when True. Defaults to False. + :keyword bool user_agent_use_env: Gets user-agent from environment. Defaults to True. + :keyword str user_agent: If specified, this will be added in front of the user agent string. + :keyword str sdk_moniker: If specified, the user agent string will be + azsdk-python-[sdk_moniker] Python/[python_version] ([platform_version]) + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_sansio.py + :start-after: [START user_agent_policy] + :end-before: [END user_agent_policy] + :language: python + :dedent: 4 + :caption: Configuring a user agent policy. + """ + + _USERAGENT = "User-Agent" + _ENV_ADDITIONAL_USER_AGENT = "AZURE_HTTP_USER_AGENT" + + def __init__( + self, base_user_agent: Optional[str] = None, **kwargs: Any + ) -> None: # pylint: disable=super-init-not-called + self.overwrite: bool = kwargs.pop("user_agent_overwrite", False) + self.use_env: bool = kwargs.pop("user_agent_use_env", True) + application_id: Optional[str] = kwargs.pop("user_agent", None) + sdk_moniker: str = kwargs.pop("sdk_moniker", "core/{}".format(azcore_version)) + + if base_user_agent: + self._user_agent = base_user_agent + else: + self._user_agent = "azsdk-python-{} Python/{} ({})".format( + sdk_moniker, platform.python_version(), platform.platform() + ) + + if application_id: + self._user_agent = "{} {}".format(application_id, self._user_agent) + + @property + def user_agent(self) -> str: + """The current user agent value. + + :return: The current user agent value. + :rtype: str + """ + if self.use_env: + add_user_agent_header = os.environ.get(self._ENV_ADDITIONAL_USER_AGENT, None) + if add_user_agent_header is not None: + return "{} {}".format(self._user_agent, add_user_agent_header) + return self._user_agent + + def add_user_agent(self, value: str) -> None: + """Add value to current user agent with a space. + :param str value: value to add to user agent. + """ + self._user_agent = "{} {}".format(self._user_agent, value) + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Modifies the User-Agent header before the request is sent. + + :param request: The PipelineRequest object + :type request: ~azure.core.pipeline.PipelineRequest + """ + http_request = request.http_request + options_dict = request.context.options + if "user_agent" in options_dict: + user_agent = options_dict.pop("user_agent") + if options_dict.pop("user_agent_overwrite", self.overwrite): + http_request.headers[self._USERAGENT] = user_agent + else: + user_agent = "{} {}".format(user_agent, self.user_agent) + http_request.headers[self._USERAGENT] = user_agent + + elif self.overwrite or self._USERAGENT not in http_request.headers: + http_request.headers[self._USERAGENT] = self.user_agent + + +class NetworkTraceLoggingPolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]): + + """The logging policy in the pipeline is used to output HTTP network trace to the configured logger. + + This accepts both global configuration, and per-request level with "enable_http_logger" + + :param bool logging_enable: Use to enable per operation. Defaults to False. + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_sansio.py + :start-after: [START network_trace_logging_policy] + :end-before: [END network_trace_logging_policy] + :language: python + :dedent: 4 + :caption: Configuring a network trace logging policy. + """ + + def __init__(self, logging_enable: bool = False, **kwargs: Any): # pylint: disable=unused-argument + self.enable_http_logger = logging_enable + + def on_request( + self, request: PipelineRequest[HTTPRequestType] + ) -> None: # pylint: disable=too-many-return-statements + """Logs HTTP request to the DEBUG logger. + + :param request: The PipelineRequest object. + :type request: ~azure.core.pipeline.PipelineRequest + """ + http_request = request.http_request + options = request.context.options + logging_enable = options.pop("logging_enable", self.enable_http_logger) + request.context["logging_enable"] = logging_enable + if logging_enable: + if not _LOGGER.isEnabledFor(logging.DEBUG): + return + + try: + log_string = "Request URL: '{}'".format(http_request.url) + log_string += "\nRequest method: '{}'".format(http_request.method) + log_string += "\nRequest headers:" + for header, value in http_request.headers.items(): + log_string += "\n '{}': '{}'".format(header, value) + log_string += "\nRequest body:" + + # We don't want to log the binary data of a file upload. + if isinstance(http_request.body, types.GeneratorType): + log_string += "\nFile upload" + _LOGGER.debug(log_string) + return + try: + if isinstance(http_request.body, types.AsyncGeneratorType): + log_string += "\nFile upload" + _LOGGER.debug(log_string) + return + except AttributeError: + pass + if http_request.body: + log_string += "\n{}".format(str(http_request.body)) + _LOGGER.debug(log_string) + return + log_string += "\nThis request has no body" + _LOGGER.debug(log_string) + except Exception as err: # pylint: disable=broad-except + _LOGGER.debug("Failed to log request: %r", err) + + def on_response( + self, + request: PipelineRequest[HTTPRequestType], + response: PipelineResponse[HTTPRequestType, HTTPResponseType], + ) -> None: + """Logs HTTP response to the DEBUG logger. + + :param request: The PipelineRequest object. + :type request: ~azure.core.pipeline.PipelineRequest + :param response: The PipelineResponse object. + :type response: ~azure.core.pipeline.PipelineResponse + """ + http_response = response.http_response + try: + logging_enable = response.context["logging_enable"] + if logging_enable: + if not _LOGGER.isEnabledFor(logging.DEBUG): + return + + log_string = "Response status: '{}'".format(http_response.status_code) + log_string += "\nResponse headers:" + for res_header, value in http_response.headers.items(): + log_string += "\n '{}': '{}'".format(res_header, value) + + # We don't want to log binary data if the response is a file. + log_string += "\nResponse content:" + pattern = re.compile(r'attachment; ?filename=["\w.]+', re.IGNORECASE) + header = http_response.headers.get("content-disposition") + + if header and pattern.match(header): + filename = header.partition("=")[2] + log_string += "\nFile attachments: {}".format(filename) + elif http_response.headers.get("content-type", "").endswith("octet-stream"): + log_string += "\nBody contains binary data." + elif http_response.headers.get("content-type", "").startswith("image"): + log_string += "\nBody contains image data." + else: + if response.context.options.get("stream", False): + log_string += "\nBody is streamable." + else: + log_string += "\n{}".format(http_response.text()) + _LOGGER.debug(log_string) + except Exception as err: # pylint: disable=broad-except + _LOGGER.debug("Failed to log response: %s", repr(err)) + + +class _HiddenClassProperties(type): + # Backward compatible for DEFAULT_HEADERS_WHITELIST + # https://github.com/Azure/azure-sdk-for-python/issues/26331 + + @property + def DEFAULT_HEADERS_WHITELIST(cls) -> Set[str]: + return cls.DEFAULT_HEADERS_ALLOWLIST + + @DEFAULT_HEADERS_WHITELIST.setter + def DEFAULT_HEADERS_WHITELIST(cls, value: Set[str]) -> None: + cls.DEFAULT_HEADERS_ALLOWLIST = value + + +class HttpLoggingPolicy( + SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType], + metaclass=_HiddenClassProperties, +): + """The Pipeline policy that handles logging of HTTP requests and responses. + + :param logger: The logger to use for logging. Default to azure.core.pipeline.policies.http_logging_policy. + :type logger: logging.Logger + """ + + DEFAULT_HEADERS_ALLOWLIST: Set[str] = set( + [ + "x-ms-request-id", + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-error-code", + "traceparent", + "Accept", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate", # OAuth Challenge header. + ] + ) + REDACTED_PLACEHOLDER: str = "REDACTED" + MULTI_RECORD_LOG: str = "AZURE_SDK_LOGGING_MULTIRECORD" + + def __init__(self, logger: Optional[logging.Logger] = None, **kwargs: Any): # pylint: disable=unused-argument + self.logger: logging.Logger = logger or logging.getLogger("azure.core.pipeline.policies.http_logging_policy") + self.allowed_query_params: Set[str] = set() + self.allowed_header_names: Set[str] = set(self.__class__.DEFAULT_HEADERS_ALLOWLIST) + + def _redact_query_param(self, key: str, value: str) -> str: + lower_case_allowed_query_params = [param.lower() for param in self.allowed_query_params] + return value if key.lower() in lower_case_allowed_query_params else HttpLoggingPolicy.REDACTED_PLACEHOLDER + + def _redact_header(self, key: str, value: str) -> str: + lower_case_allowed_header_names = [header.lower() for header in self.allowed_header_names] + return value if key.lower() in lower_case_allowed_header_names else HttpLoggingPolicy.REDACTED_PLACEHOLDER + + def on_request( # pylint: disable=too-many-return-statements + self, request: PipelineRequest[HTTPRequestType] + ) -> None: + """Logs HTTP method, url and headers. + :param request: The PipelineRequest object. + :type request: ~azure.core.pipeline.PipelineRequest + """ + http_request = request.http_request + options = request.context.options + # Get logger in my context first (request has been retried) + # then read from kwargs (pop if that's the case) + # then use my instance logger + logger = request.context.setdefault("logger", options.pop("logger", self.logger)) + + if not logger.isEnabledFor(logging.INFO): + return + + try: + parsed_url = list(urllib.parse.urlparse(http_request.url)) + parsed_qp = urllib.parse.parse_qsl(parsed_url[4], keep_blank_values=True) + filtered_qp = [(key, self._redact_query_param(key, value)) for key, value in parsed_qp] + # 4 is query + parsed_url[4] = "&".join(["=".join(part) for part in filtered_qp]) + redacted_url = urllib.parse.urlunparse(parsed_url) + + multi_record = os.environ.get(HttpLoggingPolicy.MULTI_RECORD_LOG, False) + if multi_record: + logger.info("Request URL: %r", redacted_url) + logger.info("Request method: %r", http_request.method) + logger.info("Request headers:") + for header, value in http_request.headers.items(): + value = self._redact_header(header, value) + logger.info(" %r: %r", header, value) + if isinstance(http_request.body, types.GeneratorType): + logger.info("File upload") + return + try: + if isinstance(http_request.body, types.AsyncGeneratorType): + logger.info("File upload") + return + except AttributeError: + pass + if http_request.body: + logger.info("A body is sent with the request") + return + logger.info("No body was attached to the request") + return + log_string = "Request URL: '{}'".format(redacted_url) + log_string += "\nRequest method: '{}'".format(http_request.method) + log_string += "\nRequest headers:" + for header, value in http_request.headers.items(): + value = self._redact_header(header, value) + log_string += "\n '{}': '{}'".format(header, value) + if isinstance(http_request.body, types.GeneratorType): + log_string += "\nFile upload" + logger.info(log_string) + return + try: + if isinstance(http_request.body, types.AsyncGeneratorType): + log_string += "\nFile upload" + logger.info(log_string) + return + except AttributeError: + pass + if http_request.body: + log_string += "\nA body is sent with the request" + logger.info(log_string) + return + log_string += "\nNo body was attached to the request" + logger.info(log_string) + + except Exception as err: # pylint: disable=broad-except + logger.warning("Failed to log request: %s", repr(err)) + + def on_response( + self, + request: PipelineRequest[HTTPRequestType], + response: PipelineResponse[HTTPRequestType, HTTPResponseType], + ) -> None: + http_response = response.http_response + + # Get logger in my context first (request has been retried) + # then read from kwargs (pop if that's the case) + # then use my instance logger + # If on_request was called, should always read from context + options = request.context.options + logger = request.context.setdefault("logger", options.pop("logger", self.logger)) + + try: + if not logger.isEnabledFor(logging.INFO): + return + + multi_record = os.environ.get(HttpLoggingPolicy.MULTI_RECORD_LOG, False) + if multi_record: + logger.info("Response status: %r", http_response.status_code) + logger.info("Response headers:") + for res_header, value in http_response.headers.items(): + value = self._redact_header(res_header, value) + logger.info(" %r: %r", res_header, value) + return + log_string = "Response status: {}".format(http_response.status_code) + log_string += "\nResponse headers:" + for res_header, value in http_response.headers.items(): + value = self._redact_header(res_header, value) + log_string += "\n '{}': '{}'".format(res_header, value) + logger.info(log_string) + except Exception as err: # pylint: disable=broad-except + logger.warning("Failed to log response: %s", repr(err)) + + +class ContentDecodePolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]): + """Policy for decoding unstreamed response content. + + :param response_encoding: The encoding to use if known for this service (will disable auto-detection) + :type response_encoding: str + """ + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([0-9a-z+.-]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + def __init__( + self, response_encoding: Optional[str] = None, **kwargs: Any # pylint: disable=unused-argument + ) -> None: + self._response_encoding = response_encoding + + @classmethod + def deserialize_from_text( + cls, + data: Optional[Union[AnyStr, IO[AnyStr]]], + mime_type: Optional[str] = None, + response: Optional[HTTPResponseType] = None, + ) -> Any: + """Decode response data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + If no content-type, will return the string version (not bytes, not stream) + + :param data: The data to deserialize. + :type data: str or bytes or file-like object + :param response: The HTTP response. + :type response: ~azure.core.pipeline.transport.HttpResponse + :param str mime_type: The mime type. As mime type, charset is not expected. + :param response: If passed, exception will be annotated with that response + :type response: any + :raises ~azure.core.exceptions.DecodeError: If deserialization fails + :returns: A dict (JSON), XML tree or str, depending of the mime_type + :rtype: dict[str, Any] or xml.etree.ElementTree.Element or str + """ + if not data: + return None + + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + if mime_type is None: + return data_as_str + + if cls.JSON_REGEXP.match(mime_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DecodeError( + message="JSON is invalid: {}".format(err), + response=response, + error=err, + ) from err + elif "xml" in (mime_type or []): + try: + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DecodeError("XML is invalid", response=response) from err + elif mime_type.startswith("text/"): + return data_as_str + raise DecodeError("Cannot deserialize content-type: {}".format(mime_type)) + + @classmethod + def deserialize_from_http_generics( + cls, + response: HTTPResponseType, + encoding: Optional[str] = None, + ) -> Any: + """Deserialize from HTTP response. + + Headers will tested for "content-type" + + :param response: The HTTP response + :type response: any + :param str encoding: The encoding to use if known for this service (will disable auto-detection) + :raises ~azure.core.exceptions.DecodeError: If deserialization fails + :returns: A dict (JSON), XML tree or str, depending of the mime_type + :rtype: dict[str, Any] or xml.etree.ElementTree.Element or str + """ + # Try to use content-type from headers if available + if response.content_type: + mime_type = response.content_type.split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + mime_type = "application/json" + + # Rely on transport implementation to give me "text()" decoded correctly + if hasattr(response, "read"): + # since users can call deserialize_from_http_generics by themselves + # we want to make sure our new responses are read before we try to + # deserialize. Only read sync responses since we're in a sync function + # + # Technically HttpResponse do not contain a "read()", but we don't know what + # people have been able to pass here, so keep this code for safety, + # even if it's likely dead code + if not inspect.iscoroutinefunction(response.read): # type: ignore + response.read() # type: ignore + return cls.deserialize_from_text(response.text(encoding), mime_type, response=response) + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + options = request.context.options + response_encoding = options.pop("response_encoding", self._response_encoding) + if response_encoding: + request.context["response_encoding"] = response_encoding + + def on_response( + self, + request: PipelineRequest[HTTPRequestType], + response: PipelineResponse[HTTPRequestType, HTTPResponseType], + ) -> None: + """Extract data from the body of a REST response object. + This will load the entire payload in memory. + Will follow Content-Type to parse. + We assume everything is UTF8 (BOM acceptable). + + :param request: The PipelineRequest object. + :type request: ~azure.core.pipeline.PipelineRequest + :param response: The PipelineResponse object. + :type response: ~azure.core.pipeline.PipelineResponse + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :raises xml.etree.ElementTree.ParseError: If bytes is not valid XML + :raises ~azure.core.exceptions.DecodeError: If deserialization fails + """ + # If response was asked as stream, do NOT read anything and quit now + if response.context.options.get("stream", True): + return + + response_encoding = request.context.get("response_encoding") + + response.context[self.CONTEXT_NAME] = self.deserialize_from_http_generics( + response.http_response, response_encoding + ) + + +class ProxyPolicy(SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]): + """A proxy policy. + + Dictionary mapping protocol or protocol and host to the URL of the proxy + to be used on each Request. + + :param MutableMapping proxies: Maps protocol or protocol and hostname to the URL + of the proxy. + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_sansio.py + :start-after: [START proxy_policy] + :end-before: [END proxy_policy] + :language: python + :dedent: 4 + :caption: Configuring a proxy policy. + """ + + def __init__( + self, proxies: Optional[MutableMapping[str, str]] = None, **kwargs: Any + ): # pylint: disable=unused-argument,super-init-not-called + self.proxies = proxies + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + ctxt = request.context.options + if self.proxies and "proxies" not in ctxt: + ctxt["proxies"] = self.proxies diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_utils.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1733632a9ab28f1330eeef573a7e2b98f0cdc68e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/policies/_utils.py @@ -0,0 +1,104 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import datetime +import email.utils +from typing import Optional, cast, Union +from urllib.parse import urlparse + +from azure.core.pipeline.transport import ( + HttpResponse as LegacyHttpResponse, + AsyncHttpResponse as LegacyAsyncHttpResponse, + HttpRequest as LegacyHttpRequest, +) +from azure.core.rest import HttpResponse, AsyncHttpResponse, HttpRequest + + +from ...utils._utils import _FixedOffset, case_insensitive_dict +from .. import PipelineResponse + +AllHttpResponseType = Union[HttpResponse, LegacyHttpResponse, AsyncHttpResponse, LegacyAsyncHttpResponse] +HTTPRequestType = Union[HttpRequest, LegacyHttpRequest] + + +def _parse_http_date(text: str) -> datetime.datetime: + """Parse a HTTP date format into datetime. + + :param str text: Text containing a date in HTTP format + :rtype: datetime.datetime + :return: The parsed datetime + """ + parsed_date = email.utils.parsedate_tz(text) + if not parsed_date: + raise ValueError("Invalid HTTP date") + tz_offset = cast(int, parsed_date[9]) # Look at the code, tz_offset is always an int, at worst 0 + return datetime.datetime(*parsed_date[:6], tzinfo=_FixedOffset(tz_offset / 60)) + + +def parse_retry_after(retry_after: str) -> float: + """Helper to parse Retry-After and get value in seconds. + + :param str retry_after: Retry-After header + :rtype: float + :return: Value of Retry-After in seconds. + """ + delay: float # Using the Mypy recommendation to use float for "int or float" + try: + delay = float(retry_after) + except ValueError: + # Not an integer? Try HTTP date + retry_date = _parse_http_date(retry_after) + delay = (retry_date - datetime.datetime.now(retry_date.tzinfo)).total_seconds() + return max(0, delay) + + +def get_retry_after(response: PipelineResponse[HTTPRequestType, AllHttpResponseType]) -> Optional[float]: + """Get the value of Retry-After in seconds. + + :param response: The PipelineResponse object + :type response: ~azure.core.pipeline.PipelineResponse + :return: Value of Retry-After in seconds. + :rtype: float or None + """ + headers = case_insensitive_dict(response.http_response.headers) + retry_after = headers.get("retry-after") + if retry_after: + return parse_retry_after(retry_after) + for ms_header in ["retry-after-ms", "x-ms-retry-after-ms"]: + retry_after = headers.get(ms_header) + if retry_after: + parsed_retry_after = parse_retry_after(retry_after) + return parsed_retry_after / 1000.0 + return None + + +def get_domain(url: str) -> str: + """Get the domain of an url. + + :param str url: The url. + :rtype: str + :return: The domain of the url. + """ + return str(urlparse(url).netloc).lower() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..08b2fb4e083b10d41eabb4a8b5309d748dfe4698 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/__init__.py @@ -0,0 +1,120 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from typing import List, Optional, Any +from ._base import HttpTransport, HttpRequest, HttpResponse +from ._base_async import AsyncHttpTransport, AsyncHttpResponse + +# pylint: disable=undefined-all-variable + +__all__ = [ + "HttpTransport", + "HttpRequest", + "HttpResponse", + "RequestsTransport", + "RequestsTransportResponse", + "AsyncHttpTransport", + "AsyncHttpResponse", + "AsyncioRequestsTransport", + "AsyncioRequestsTransportResponse", + "TrioRequestsTransport", + "TrioRequestsTransportResponse", + "AioHttpTransport", + "AioHttpTransportResponse", +] + +# pylint: disable=unused-import, redefined-outer-name, no-member, too-many-statements, too-many-branches + + +def __dir__() -> List[str]: + return __all__ + + +# To do nice overloads, need https://github.com/python/mypy/issues/8203 + + +def __getattr__(name: str): + transport: Optional[Any] = None + if name == "AsyncioRequestsTransport": + try: + from ._requests_asyncio import AsyncioRequestsTransport + + transport = AsyncioRequestsTransport + except ImportError as err: + raise ImportError("requests package is not installed") from err + if name == "AsyncioRequestsTransportResponse": + try: + from ._requests_asyncio import AsyncioRequestsTransportResponse + + transport = AsyncioRequestsTransportResponse + except ImportError as err: + raise ImportError("requests package is not installed") from err + if name == "RequestsTransport": + try: + from ._requests_basic import RequestsTransport + + transport = RequestsTransport + except ImportError as err: + raise ImportError("requests package is not installed") from err + if name == "RequestsTransportResponse": + try: + from ._requests_basic import RequestsTransportResponse + + transport = RequestsTransportResponse + except ImportError as err: + raise ImportError("requests package is not installed") from err + if name == "AioHttpTransport": + try: + from ._aiohttp import AioHttpTransport + + transport = AioHttpTransport + except ImportError as err: + raise ImportError("aiohttp package is not installed") from err + if name == "AioHttpTransportResponse": + try: + from ._aiohttp import AioHttpTransportResponse + + transport = AioHttpTransportResponse + except ImportError as err: + raise ImportError("aiohttp package is not installed") from err + if name == "TrioRequestsTransport": + try: + from ._requests_trio import TrioRequestsTransport + + transport = TrioRequestsTransport + except ImportError as ex: + if ex.msg.endswith("'requests'"): + raise ImportError("requests package is not installed") from ex + raise ImportError("trio package is not installed") from ex + if name == "TrioRequestsTransportResponse": + try: + from ._requests_trio import TrioRequestsTransportResponse + + transport = TrioRequestsTransportResponse + except ImportError as err: + raise ImportError("trio package is not installed") from err + if transport: + return transport + raise AttributeError(f"module 'azure.core.pipeline.transport' has no attribute {name}") diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_aiohttp.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_aiohttp.py new file mode 100644 index 0000000000000000000000000000000000000000..01ca01c081babe6e51bdfc81b2050e6ccb94868f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_aiohttp.py @@ -0,0 +1,550 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from __future__ import annotations +import sys +from typing import ( + Any, + Optional, + AsyncIterator as AsyncIteratorType, + TYPE_CHECKING, + overload, + cast, + Union, + Type, + MutableMapping, +) +from types import TracebackType +from collections.abc import AsyncIterator + +import logging +import asyncio +import codecs +import aiohttp +import aiohttp.client_exceptions +from multidict import CIMultiDict + +from azure.core.configuration import ConnectionConfiguration +from azure.core.exceptions import ( + ServiceRequestError, + ServiceResponseError, + IncompleteReadError, +) +from azure.core.pipeline import AsyncPipeline + +from ._base import HttpRequest +from ._base_async import AsyncHttpTransport, AsyncHttpResponse, _ResponseStopIteration +from ...utils._pipeline_transport_rest_shared import _aiohttp_body_helper, get_file_items +from .._tools import is_rest as _is_rest +from .._tools_async import ( + handle_no_stream_rest_response as _handle_no_stream_rest_response, +) + +if TYPE_CHECKING: + from ...rest import ( + HttpRequest as RestHttpRequest, + AsyncHttpResponse as RestAsyncHttpResponse, + ) + from ...rest._aiohttp import RestAioHttpTransportResponse + +# Matching requests, because why not? +CONTENT_CHUNK_SIZE = 10 * 1024 +_LOGGER = logging.getLogger(__name__) + + +class AioHttpTransport(AsyncHttpTransport): + """AioHttp HTTP sender implementation. + + Fully asynchronous implementation using the aiohttp library. + + :keyword session: The client session. + :paramtype session: ~aiohttp.ClientSession + :keyword bool session_owner: Session owner. Defaults True. + + :keyword bool use_env_settings: Uses proxy settings from environment. Defaults to True. + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_async.py + :start-after: [START aiohttp] + :end-before: [END aiohttp] + :language: python + :dedent: 4 + :caption: Asynchronous transport with aiohttp. + """ + + def __init__( + self, + *, + session: Optional[aiohttp.ClientSession] = None, + loop=None, + session_owner: bool = True, + **kwargs, + ): + if loop and sys.version_info >= (3, 10): + raise ValueError("Starting with Python 3.10, asyncio doesn’t support loop as a parameter anymore") + self._loop = loop + self._session_owner = session_owner + self.session = session + if not self._session_owner and not self.session: + raise ValueError("session_owner cannot be False if no session is provided") + self.connection_config = ConnectionConfiguration(**kwargs) + self._use_env_settings = kwargs.pop("use_env_settings", True) + + async def __aenter__(self): + await self.open() + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ) -> None: + await self.close() + + async def open(self): + """Opens the connection.""" + if not self.session and self._session_owner: + jar = aiohttp.DummyCookieJar() + clientsession_kwargs = { + "trust_env": self._use_env_settings, + "cookie_jar": jar, + "auto_decompress": False, + } + if self._loop is not None: + clientsession_kwargs["loop"] = self._loop + self.session = aiohttp.ClientSession(**clientsession_kwargs) + # pyright has trouble to understand that self.session is not None, since we raised at worst in the init + self.session = cast(aiohttp.ClientSession, self.session) + await self.session.__aenter__() + + async def close(self): + """Closes the connection.""" + if self._session_owner and self.session: + await self.session.close() + self._session_owner = False + self.session = None + + def _build_ssl_config(self, cert, verify): + """Build the SSL configuration. + + :param tuple cert: Cert information + :param bool verify: SSL verification or path to CA file or directory + :rtype: bool or str or ssl.SSLContext + :return: SSL Configuration + """ + ssl_ctx = None + + if cert or verify not in (True, False): + import ssl + + if verify not in (True, False): + ssl_ctx = ssl.create_default_context(cafile=verify) + else: + ssl_ctx = ssl.create_default_context() + if cert: + ssl_ctx.load_cert_chain(*cert) + return ssl_ctx + return verify + + def _get_request_data(self, request): + """Get the request data. + + :param request: The request object + :type request: ~azure.core.pipeline.transport.HttpRequest or ~azure.core.rest.HttpRequest + :rtype: bytes or ~aiohttp.FormData + :return: The request data + """ + if request.files: + form_data = aiohttp.FormData(request.data or {}) + for form_file, data in get_file_items(request.files): + content_type = data[2] if len(data) > 2 else None + try: + form_data.add_field(form_file, data[1], filename=data[0], content_type=content_type) + except IndexError as err: + raise ValueError("Invalid formdata formatting: {}".format(data)) from err + return form_data + return request.data + + @overload + async def send( + self, + request: HttpRequest, + *, + stream: bool = False, + proxies: Optional[MutableMapping[str, str]] = None, + **config: Any, + ) -> AsyncHttpResponse: + """Send the request using this HTTP sender. + + Will pre-load the body into memory to be available with a sync method. + Pass stream=True to avoid this behavior. + + :param request: The HttpRequest object + :type request: ~azure.core.pipeline.transport.HttpRequest + :return: The AsyncHttpResponse + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + + :keyword bool stream: Defaults to False. + :keyword MutableMapping proxies: dict of proxy to used based on protocol. Proxy is a dict (protocol, url) + """ + + @overload + async def send( + self, + request: RestHttpRequest, + *, + stream: bool = False, + proxies: Optional[MutableMapping[str, str]] = None, + **config: Any, + ) -> RestAsyncHttpResponse: + """Send the `azure.core.rest` request using this HTTP sender. + + Will pre-load the body into memory to be available with a sync method. + Pass stream=True to avoid this behavior. + + :param request: The HttpRequest object + :type request: ~azure.core.rest.HttpRequest + :return: The AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse + + :keyword bool stream: Defaults to False. + :keyword MutableMapping proxies: dict of proxy to used based on protocol. Proxy is a dict (protocol, url) + """ + + async def send( + self, + request: Union[HttpRequest, RestHttpRequest], + *, + stream: bool = False, + proxies: Optional[MutableMapping[str, str]] = None, + **config, + ) -> Union[AsyncHttpResponse, RestAsyncHttpResponse]: + """Send the request using this HTTP sender. + + Will pre-load the body into memory to be available with a sync method. + Pass stream=True to avoid this behavior. + + :param request: The HttpRequest object + :type request: ~azure.core.rest.HttpRequest + :return: The AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse + + :keyword bool stream: Defaults to False. + :keyword MutableMapping proxies: dict of proxy to used based on protocol. Proxy is a dict (protocol, url) + """ + await self.open() + try: + auto_decompress = self.session.auto_decompress # type: ignore + except AttributeError: + # auto_decompress is introduced in aiohttp 3.7. We need this to handle aiohttp 3.6-. + auto_decompress = False + + proxy = config.pop("proxy", None) + if proxies and not proxy: + # aiohttp needs a single proxy, so iterating until we found the right protocol + + # Sort by longest string first, so "http" is not used for "https" ;-) + for protocol in sorted(proxies.keys(), reverse=True): + if request.url.startswith(protocol): + proxy = proxies[protocol] + break + + response: Optional[Union[AsyncHttpResponse, RestAsyncHttpResponse]] = None + ssl = self._build_ssl_config( + cert=config.pop("connection_cert", self.connection_config.cert), + verify=config.pop("connection_verify", self.connection_config.verify), + ) + # If ssl=True, we just use default ssl context from aiohttp + if ssl is not True: + config["ssl"] = ssl + # If we know for sure there is not body, disable "auto content type" + # Otherwise, aiohttp will send "application/octet-stream" even for empty POST request + # and that break services like storage signature + if not request.data and not request.files: + config["skip_auto_headers"] = ["Content-Type"] + try: + stream_response = stream + timeout = config.pop("connection_timeout", self.connection_config.timeout) + read_timeout = config.pop("read_timeout", self.connection_config.read_timeout) + socket_timeout = aiohttp.ClientTimeout(sock_connect=timeout, sock_read=read_timeout) + result = await self.session.request( # type: ignore + request.method, + request.url, + headers=request.headers, + data=self._get_request_data(request), + timeout=socket_timeout, + allow_redirects=False, + proxy=proxy, + **config, + ) + if _is_rest(request): + from azure.core.rest._aiohttp import RestAioHttpTransportResponse + + response = RestAioHttpTransportResponse( + request=request, + internal_response=result, + block_size=self.connection_config.data_block_size, + decompress=not auto_decompress, + ) + if not stream_response: + await _handle_no_stream_rest_response(response) + else: + # Given the associated "if", this else is legacy implementation + # but mypy do not know it, so using a cast + request = cast(HttpRequest, request) + response = AioHttpTransportResponse( + request, + result, + self.connection_config.data_block_size, + decompress=not auto_decompress, + ) + if not stream_response: + await response.load_body() + except aiohttp.client_exceptions.ClientResponseError as err: + raise ServiceResponseError(err, error=err) from err + except asyncio.TimeoutError as err: + raise ServiceResponseError(err, error=err) from err + except aiohttp.client_exceptions.ClientError as err: + raise ServiceRequestError(err, error=err) from err + return response + + +class AioHttpStreamDownloadGenerator(AsyncIterator): + """Streams the response body data. + + :param pipeline: The pipeline object + :type pipeline: ~azure.core.pipeline.AsyncPipeline + :param response: The client response object. + :type response: ~azure.core.rest.AsyncHttpResponse + :keyword bool decompress: If True which is default, will attempt to decode the body based + on the *content-encoding* header. + """ + + @overload + def __init__( + self, + pipeline: AsyncPipeline[HttpRequest, AsyncHttpResponse], + response: AioHttpTransportResponse, + *, + decompress: bool = True, + ) -> None: + ... + + @overload + def __init__( + self, + pipeline: AsyncPipeline[RestHttpRequest, RestAsyncHttpResponse], + response: RestAioHttpTransportResponse, + *, + decompress: bool = True, + ) -> None: + ... + + def __init__( + self, + pipeline: AsyncPipeline, + response: Union[AioHttpTransportResponse, RestAioHttpTransportResponse], + *, + decompress: bool = True, + ) -> None: + self.pipeline = pipeline + self.request = response.request + self.response = response + self.block_size = response.block_size + self._decompress = decompress + internal_response = response.internal_response + self.content_length = int(internal_response.headers.get("Content-Length", 0)) + self._decompressor = None + + def __len__(self): + return self.content_length + + async def __anext__(self): + internal_response = self.response.internal_response + try: + chunk = await internal_response.content.read(self.block_size) + if not chunk: + raise _ResponseStopIteration() + if not self._decompress: + return chunk + enc = internal_response.headers.get("Content-Encoding") + if not enc: + return chunk + enc = enc.lower() + if enc in ("gzip", "deflate"): + if not self._decompressor: + import zlib + + zlib_mode = (16 + zlib.MAX_WBITS) if enc == "gzip" else -zlib.MAX_WBITS + self._decompressor = zlib.decompressobj(wbits=zlib_mode) + chunk = self._decompressor.decompress(chunk) + return chunk + except _ResponseStopIteration: + internal_response.close() + raise StopAsyncIteration() # pylint: disable=raise-missing-from + except aiohttp.client_exceptions.ClientPayloadError as err: + # This is the case that server closes connection before we finish the reading. aiohttp library + # raises ClientPayloadError. + _LOGGER.warning("Incomplete download: %s", err) + internal_response.close() + raise IncompleteReadError(err, error=err) from err + except aiohttp.client_exceptions.ClientResponseError as err: + raise ServiceResponseError(err, error=err) from err + except asyncio.TimeoutError as err: + raise ServiceResponseError(err, error=err) from err + except aiohttp.client_exceptions.ClientError as err: + raise ServiceRequestError(err, error=err) from err + except Exception as err: + _LOGGER.warning("Unable to stream download: %s", err) + internal_response.close() + raise + + +class AioHttpTransportResponse(AsyncHttpResponse): + """Methods for accessing response body data. + + :param request: The HttpRequest object + :type request: ~azure.core.pipeline.transport.HttpRequest + :param aiohttp_response: Returned from ClientSession.request(). + :type aiohttp_response: aiohttp.ClientResponse object + :param block_size: block size of data sent over connection. + :type block_size: int + :keyword bool decompress: If True which is default, will attempt to decode the body based + on the *content-encoding* header. + """ + + def __init__( + self, + request: HttpRequest, + aiohttp_response: aiohttp.ClientResponse, + block_size: Optional[int] = None, + *, + decompress: bool = True, + ) -> None: + super(AioHttpTransportResponse, self).__init__(request, aiohttp_response, block_size=block_size) + # https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientResponse + self.status_code = aiohttp_response.status + self.headers = CIMultiDict(aiohttp_response.headers) + self.reason = aiohttp_response.reason + self.content_type = aiohttp_response.headers.get("content-type") + self._content = None + self._decompressed_content = False + self._decompress = decompress + + def body(self) -> bytes: + """Return the whole body as bytes in memory. + + :rtype: bytes + :return: The whole response body. + """ + return _aiohttp_body_helper(self) + + def text(self, encoding: Optional[str] = None) -> str: + """Return the whole body as a string. + + If encoding is not provided, rely on aiohttp auto-detection. + + :param str encoding: The encoding to apply. + :rtype: str + :return: The whole response body as a string. + """ + # super().text detects charset based on self._content() which is compressed + # implement the decoding explicitly here + body = self.body() + + ctype = self.headers.get(aiohttp.hdrs.CONTENT_TYPE, "").lower() + mimetype = aiohttp.helpers.parse_mimetype(ctype) + + if not encoding: + # extract encoding from mimetype, if caller does not specify + encoding = mimetype.parameters.get("charset") + if encoding: + try: + codecs.lookup(encoding) + except LookupError: + encoding = None + if not encoding: + if mimetype.type == "application" and mimetype.subtype in ["json", "rdap"]: + # RFC 7159 states that the default encoding is UTF-8. + # RFC 7483 defines application/rdap+json + encoding = "utf-8" + elif body is None: + raise RuntimeError("Cannot guess the encoding of a not yet read body") + else: + try: + import cchardet as chardet + except ImportError: # pragma: no cover + try: + import chardet # type: ignore + except ImportError: # pragma: no cover + import charset_normalizer as chardet # type: ignore[no-redef] + # While "detect" can return a dict of float, in this context this won't happen + # The cast is for pyright to be happy + encoding = cast(Optional[str], chardet.detect(body)["encoding"]) + if encoding == "utf-8" or encoding is None: + encoding = "utf-8-sig" + + return body.decode(encoding) + + async def load_body(self) -> None: + """Load in memory the body, so it could be accessible from sync methods.""" + try: + self._content = await self.internal_response.read() + except aiohttp.client_exceptions.ClientPayloadError as err: + # This is the case that server closes connection before we finish the reading. aiohttp library + # raises ClientPayloadError. + raise IncompleteReadError(err, error=err) from err + except aiohttp.client_exceptions.ClientResponseError as err: + raise ServiceResponseError(err, error=err) from err + except asyncio.TimeoutError as err: + raise ServiceResponseError(err, error=err) from err + except aiohttp.client_exceptions.ClientError as err: + raise ServiceRequestError(err, error=err) from err + + def stream_download( + self, pipeline: AsyncPipeline[HttpRequest, AsyncHttpResponse], *, decompress: bool = True, **kwargs + ) -> AsyncIteratorType[bytes]: + """Generator for streaming response body data. + + :param pipeline: The pipeline object + :type pipeline: azure.core.pipeline.AsyncPipeline + :keyword bool decompress: If True which is default, will attempt to decode the body based + on the *content-encoding* header. + :rtype: AsyncIterator[bytes] + :return: An iterator of bytes chunks. + """ + return AioHttpStreamDownloadGenerator(pipeline, self, decompress=decompress, **kwargs) + + def __getstate__(self): + # Be sure body is loaded in memory, otherwise not pickable and let it throw + self.body() + + state = self.__dict__.copy() + # Remove the unpicklable entries. + state["internal_response"] = None # aiohttp response are not pickable (see headers comments) + state["headers"] = CIMultiDict(self.headers) # MultiDictProxy is not pickable + return state diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..6adaede9f640f123c800ae224325d27e4e72c884 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_base.py @@ -0,0 +1,863 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from __future__ import annotations +import abc +from email.message import Message +import json +import logging +import time +import copy +from urllib.parse import urlparse +import xml.etree.ElementTree as ET + +from typing import ( + Generic, + TypeVar, + IO, + Union, + Any, + Mapping, + Optional, + Tuple, + Iterator, + Type, + Dict, + List, + Sequence, + MutableMapping, + ContextManager, + TYPE_CHECKING, +) + +from http.client import HTTPResponse as _HTTPResponse + +from azure.core.exceptions import HttpResponseError +from azure.core.pipeline.policies import SansIOHTTPPolicy +from ...utils._utils import case_insensitive_dict +from ...utils._pipeline_transport_rest_shared import ( + _format_parameters_helper, + _prepare_multipart_body_helper, + _serialize_request, + _format_data_helper, + BytesIOSocket, + _decode_parts_helper, + _get_raw_parts_helper, + _parts_helper, +) + + +HTTPResponseType = TypeVar("HTTPResponseType") +HTTPRequestType = TypeVar("HTTPRequestType") +DataType = Union[bytes, str, Dict[str, Union[str, int]]] + +if TYPE_CHECKING: + # We need a transport to define a pipeline, this "if" avoid a circular import + from azure.core.pipeline import Pipeline + from azure.core.rest._helpers import FileContent + +_LOGGER = logging.getLogger(__name__) + +binary_type = str + + +def _format_url_section(template, **kwargs: Dict[str, str]) -> str: + """String format the template with the kwargs, auto-skip sections of the template that are NOT in the kwargs. + + By default in Python, "format" will raise a KeyError if a template element is not found. Here the section between + the slashes will be removed from the template instead. + + This is used for API like Storage, where when Swagger has template section not defined as parameter. + + :param str template: a string template to fill + :rtype: str + :returns: Template completed + """ + last_template = template + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{{{}}}".format(key.args[0]) not in c] + template = "/".join(components) + if last_template == template: + raise ValueError( + f"The value provided for the url part '{template}' was incorrect, and resulted in an invalid url" + ) from key + last_template = template + return last_template + + +def _urljoin(base_url: str, stub_url: str) -> str: + """Append to end of base URL without losing query parameters. + + :param str base_url: The base URL. + :param str stub_url: Section to append to the end of the URL path. + :returns: The updated URL. + :rtype: str + """ + parsed_base_url = urlparse(base_url) + + # Can't use "urlparse" on a partial url, we get incorrect parsing for things like + # document:build?format=html&api-version=2019-05-01 + split_url = stub_url.split("?", 1) + stub_url_path = split_url.pop(0) + stub_url_query = split_url.pop() if split_url else None + + # Note that _replace is a public API named that way to avoid conflicts in namedtuple + # https://docs.python.org/3/library/collections.html?highlight=namedtuple#collections.namedtuple + parsed_base_url = parsed_base_url._replace( + path=parsed_base_url.path.rstrip("/") + "/" + stub_url_path, + ) + if stub_url_query: + query_params = [stub_url_query] + if parsed_base_url.query: + query_params.insert(0, parsed_base_url.query) + parsed_base_url = parsed_base_url._replace(query="&".join(query_params)) + return parsed_base_url.geturl() + + +class HttpTransport(ContextManager["HttpTransport"], abc.ABC, Generic[HTTPRequestType, HTTPResponseType]): + """An http sender ABC.""" + + @abc.abstractmethod + def send(self, request: HTTPRequestType, **kwargs: Any) -> HTTPResponseType: + """Send the request using this HTTP sender. + + :param request: The pipeline request object + :type request: ~azure.core.transport.HTTPRequest + :return: The pipeline response object. + :rtype: ~azure.core.pipeline.transport.HttpResponse + """ + + @abc.abstractmethod + def open(self) -> None: + """Assign new session if one does not already exist.""" + + @abc.abstractmethod + def close(self) -> None: + """Close the session if it is not externally owned.""" + + def sleep(self, duration: float) -> None: + """Sleep for the specified duration. + + You should always ask the transport to sleep, and not call directly + the stdlib. This is mostly important in async, as the transport + may not use asyncio but other implementations like trio and they have their own + way to sleep, but to keep design + consistent, it's cleaner to always ask the transport to sleep and let the transport + implementor decide how to do it. + + :param float duration: The number of seconds to sleep. + """ + time.sleep(duration) + + +class HttpRequest: + """Represents an HTTP request. + + URL can be given without query parameters, to be added later using "format_parameters". + + :param str method: HTTP method (GET, HEAD, etc.) + :param str url: At least complete scheme/host/path + :param dict[str,str] headers: HTTP headers + :param files: Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart + encoding upload. ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple + ``('filename', fileobj, 'content_type')`` or a 4-tuple + ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string + defining the content type of the given file and ``custom_headers`` + a dict-like object containing additional headers to add for the file. + :type files: dict[str, tuple[str, IO, str, dict]] or dict[str, IO] + :param data: Body to be sent. + :type data: bytes or dict (for form) + """ + + def __init__( + self, + method: str, + url: str, + headers: Optional[Mapping[str, str]] = None, + files: Optional[Any] = None, + data: Optional[DataType] = None, + ) -> None: + self.method = method + self.url = url + self.headers: MutableMapping[str, str] = case_insensitive_dict(headers) + self.files: Optional[Any] = files + self.data: Optional[DataType] = data + self.multipart_mixed_info: Optional[Tuple[Sequence[Any], Sequence[Any], Optional[str], Dict[str, Any]]] = None + + def __repr__(self) -> str: + return "".format(self.method, self.url) + + def __deepcopy__(self, memo: Optional[Dict[int, Any]] = None) -> "HttpRequest": + try: + data = copy.deepcopy(self.body, memo) + files = copy.deepcopy(self.files, memo) + request = HttpRequest(self.method, self.url, self.headers, files, data) + request.multipart_mixed_info = self.multipart_mixed_info + return request + except (ValueError, TypeError): + return copy.copy(self) + + @property + def query(self) -> Dict[str, str]: + """The query parameters of the request as a dict. + + :rtype: dict[str, str] + :return: The query parameters of the request as a dict. + """ + query = urlparse(self.url).query + if query: + return {p[0]: p[-1] for p in [p.partition("=") for p in query.split("&")]} + return {} + + @property + def body(self) -> Optional[DataType]: + """Alias to data. + + :rtype: bytes or str or dict or None + :return: The body of the request. + """ + return self.data + + @body.setter + def body(self, value: Optional[DataType]) -> None: + self.data = value + + @staticmethod + def _format_data(data: Union[str, IO]) -> Union[Tuple[Optional[str], str], Tuple[Optional[str], FileContent, str]]: + """Format field data according to whether it is a stream or + a string for a form-data request. + + :param data: The request field data. + :type data: str or file-like object. + :rtype: tuple[str, IO, str] or tuple[None, str] + :return: A tuple of (data name, data IO, "application/octet-stream") or (None, data str) + """ + return _format_data_helper(data) + + def format_parameters(self, params: Dict[str, str]) -> None: + """Format parameters into a valid query string. + It's assumed all parameters have already been quoted as + valid URL strings. + + :param dict params: A dictionary of parameters. + """ + return _format_parameters_helper(self, params) + + def set_streamed_data_body(self, data: Any) -> None: + """Set a streamable data body. + + :param data: The request field data. + :type data: stream or generator or asyncgenerator + """ + if not isinstance(data, binary_type) and not any( + hasattr(data, attr) for attr in ["read", "__iter__", "__aiter__"] + ): + raise TypeError("A streamable data source must be an open file-like object or iterable.") + self.data = data + self.files = None + + def set_text_body(self, data: str) -> None: + """Set a text as body of the request. + + :param data: A text to send as body. + :type data: str + """ + if data is None: + self.data = None + else: + self.data = data + self.headers["Content-Length"] = str(len(self.data)) + self.files = None + + def set_xml_body(self, data: Any) -> None: + """Set an XML element tree as the body of the request. + + :param data: The request field data. + :type data: XML node + """ + if data is None: + self.data = None + else: + bytes_data: bytes = ET.tostring(data, encoding="utf8") + self.data = bytes_data.replace(b"encoding='utf8'", b"encoding='utf-8'") + self.headers["Content-Length"] = str(len(self.data)) + self.files = None + + def set_json_body(self, data: Any) -> None: + """Set a JSON-friendly object as the body of the request. + + :param data: A JSON serializable object + :type data: dict + """ + if data is None: + self.data = None + else: + self.data = json.dumps(data) + self.headers["Content-Length"] = str(len(self.data)) + self.files = None + + def set_formdata_body(self, data: Optional[Dict[str, str]] = None) -> None: + """Set form-encoded data as the body of the request. + + :param data: The request field data. + :type data: dict + """ + if data is None: + data = {} + content_type = self.headers.pop("Content-Type", None) if self.headers else None + + if content_type and content_type.lower() == "application/x-www-form-urlencoded": + self.data = {f: d for f, d in data.items() if d is not None} + self.files = None + else: # Assume "multipart/form-data" + self.files = {f: self._format_data(d) for f, d in data.items() if d is not None} + self.data = None + + def set_bytes_body(self, data: bytes) -> None: + """Set generic bytes as the body of the request. + + Will set content-length. + + :param data: The request field data. + :type data: bytes + """ + if data: + self.headers["Content-Length"] = str(len(data)) + self.data = data + self.files = None + + def set_multipart_mixed( + self, + *requests: "HttpRequest", + policies: Optional[List[SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]]] = None, + boundary: Optional[str] = None, + **kwargs: Any, + ) -> None: + """Set the part of a multipart/mixed. + + Only supported args for now are HttpRequest objects. + + boundary is optional, and one will be generated if you don't provide one. + Note that no verification are made on the boundary, this is considered advanced + enough so you know how to respect RFC1341 7.2.1 and provide a correct boundary. + + Any additional kwargs will be passed into the pipeline context for per-request policy + configuration. + + :param requests: The requests to add to the multipart/mixed + :type requests: ~azure.core.pipeline.transport.HttpRequest + :keyword list[SansIOHTTPPolicy] policies: SansIOPolicy to apply at preparation time + :keyword str boundary: Optional boundary + """ + policies = policies or [] + self.multipart_mixed_info = ( + requests, + policies, + boundary, + kwargs, + ) + + def prepare_multipart_body(self, content_index: int = 0) -> int: + """Will prepare the body of this request according to the multipart information. + + This call assumes the on_request policies have been applied already in their + correct context (sync/async) + + Does nothing if "set_multipart_mixed" was never called. + + :param int content_index: The current index of parts within the batch message. + :returns: The updated index after all parts in this request have been added. + :rtype: int + """ + return _prepare_multipart_body_helper(self, content_index) + + def serialize(self) -> bytes: + """Serialize this request using application/http spec. + + :rtype: bytes + :return: The requests serialized as HTTP low-level message in bytes. + """ + return _serialize_request(self) + + +class _HttpResponseBase: + """Represent a HTTP response. + + No body is defined here on purpose, since async pipeline + will provide async ways to access the body + Full in-memory using "body" as bytes. + + :param request: The request. + :type request: ~azure.core.pipeline.transport.HttpRequest + :param internal_response: The object returned from the HTTP library. + :type internal_response: any + :param int block_size: Defaults to 4096 bytes. + """ + + def __init__( + self, + request: "HttpRequest", + internal_response: Any, + block_size: Optional[int] = None, + ) -> None: + self.request: HttpRequest = request + self.internal_response = internal_response + # This is actually never None, and set by all implementations after the call to + # __init__ of this class. This class is also a legacy impl, so it's risky to change it + # for low benefits The new "rest" implementation does define correctly status_code + # as non-optional. + self.status_code: int = None # type: ignore + self.headers: MutableMapping[str, str] = {} + self.reason: Optional[str] = None + self.content_type: Optional[str] = None + self.block_size: int = block_size or 4096 # Default to same as Requests + + def body(self) -> bytes: + """Return the whole body as bytes in memory. + + Sync implementer should load the body in memory if they can. + Async implementer should rely on async load_body to have been called first. + + :rtype: bytes + :return: The whole body as bytes in memory. + """ + raise NotImplementedError() + + def text(self, encoding: Optional[str] = None) -> str: + """Return the whole body as a string. + + .. seealso:: ~body() + + :param str encoding: The encoding to apply. If None, use "utf-8" with BOM parsing (utf-8-sig). + Implementation can be smarter if they want (using headers or chardet). + :rtype: str + :return: The whole body as a string. + """ + if encoding == "utf-8" or encoding is None: + encoding = "utf-8-sig" + return self.body().decode(encoding) + + def _decode_parts( + self, + message: Message, + http_response_type: Type["_HttpResponseBase"], + requests: Sequence[HttpRequest], + ) -> List["HttpResponse"]: + """Rebuild an HTTP response from pure string. + + :param ~email.message.Message message: The HTTP message as an email object + :param type http_response_type: The type of response to return + :param list[HttpRequest] requests: The requests that were batched together + :rtype: list[HttpResponse] + :return: The list of HttpResponse + """ + return _decode_parts_helper(self, message, http_response_type, requests, _deserialize_response) + + def _get_raw_parts( + self, http_response_type: Optional[Type["_HttpResponseBase"]] = None + ) -> Iterator["HttpResponse"]: + """Assuming this body is multipart, return the iterator or parts. + + If parts are application/http use http_response_type or HttpClientTransportResponse + as envelope. + + :param type http_response_type: The type of response to return + :rtype: iterator[HttpResponse] + :return: The iterator of HttpResponse + """ + return _get_raw_parts_helper(self, http_response_type or HttpClientTransportResponse) + + def raise_for_status(self) -> None: + """Raises an HttpResponseError if the response has an error status code. + If response is good, does nothing. + """ + if not self.status_code or self.status_code >= 400: + raise HttpResponseError(response=self) + + def __repr__(self) -> str: + content_type_str = ", Content-Type: {}".format(self.content_type) if self.content_type else "" + return "<{}: {} {}{}>".format(type(self).__name__, self.status_code, self.reason, content_type_str) + + +class HttpResponse(_HttpResponseBase): # pylint: disable=abstract-method + def stream_download(self, pipeline: Pipeline[HttpRequest, "HttpResponse"], **kwargs: Any) -> Iterator[bytes]: + """Generator for streaming request body data. + + Should be implemented by sub-classes if streaming download + is supported. + + :param pipeline: The pipeline object + :type pipeline: ~azure.core.pipeline.Pipeline + :rtype: iterator[bytes] + :return: The generator of bytes connected to the socket + """ + raise NotImplementedError("stream_download is not implemented.") + + def parts(self) -> Iterator["HttpResponse"]: + """Assuming the content-type is multipart/mixed, will return the parts as an iterator. + + :rtype: iterator[HttpResponse] + :return: The iterator of HttpResponse if request was multipart/mixed + :raises ValueError: If the content is not multipart/mixed + """ + return _parts_helper(self) + + +class _HttpClientTransportResponse(_HttpResponseBase): + """Create a HTTPResponse from an http.client response. + + Body will NOT be read by the constructor. Call "body()" to load the body in memory if necessary. + + :param HttpRequest request: The request. + :param httpclient_response: The object returned from an HTTP(S)Connection from http.client + :type httpclient_response: http.client.HTTPResponse + """ + + def __init__(self, request, httpclient_response): + super(_HttpClientTransportResponse, self).__init__(request, httpclient_response) + self.status_code = httpclient_response.status + self.headers = case_insensitive_dict(httpclient_response.getheaders()) + self.reason = httpclient_response.reason + self.content_type = self.headers.get("Content-Type") + self.data = None + + def body(self): + if self.data is None: + self.data = self.internal_response.read() + return self.data + + +class HttpClientTransportResponse(_HttpClientTransportResponse, HttpResponse): # pylint: disable=abstract-method + """Create a HTTPResponse from an http.client response. + + Body will NOT be read by the constructor. Call "body()" to load the body in memory if necessary. + """ + + +def _deserialize_response(http_response_as_bytes, http_request, http_response_type=HttpClientTransportResponse): + """Deserialize a HTTPResponse from a string. + + :param bytes http_response_as_bytes: The HTTP response as bytes. + :param HttpRequest http_request: The request to store in the response. + :param type http_response_type: The type of response to return + :rtype: HttpResponse + :return: The HTTP response from those low-level bytes. + """ + local_socket = BytesIOSocket(http_response_as_bytes) + response = _HTTPResponse(local_socket, method=http_request.method) + response.begin() + return http_response_type(http_request, response) + + +class PipelineClientBase: + """Base class for pipeline clients. + + :param str base_url: URL for the request. + """ + + def __init__(self, base_url: str): + self._base_url = base_url + + def _request( + self, + method: str, + url: str, + params: Optional[Dict[str, str]], + headers: Optional[Dict[str, str]], + content: Any, + form_content: Optional[Dict[str, Any]], + stream_content: Any, + ) -> HttpRequest: + """Create HttpRequest object. + + If content is not None, guesses will be used to set the right body: + - If content is an XML tree, will serialize as XML + - If content-type starts by "text/", set the content as text + - Else, try JSON serialization + + :param str method: HTTP method (GET, HEAD, etc.) + :param str url: URL for the request. + :param dict params: URL query parameters. + :param dict headers: Headers + :param content: The body content + :type content: bytes or str or dict + :param dict form_content: Form content + :param stream_content: The body content as a stream + :type stream_content: stream or generator or asyncgenerator + :return: An HttpRequest object + :rtype: ~azure.core.pipeline.transport.HttpRequest + """ + request = HttpRequest(method, self.format_url(url)) + + if params: + request.format_parameters(params) + + if headers: + request.headers.update(headers) + + if content is not None: + content_type = request.headers.get("Content-Type") + if isinstance(content, ET.Element): + request.set_xml_body(content) + # https://github.com/Azure/azure-sdk-for-python/issues/12137 + # A string is valid JSON, make the difference between text + # and a plain JSON string. + # Content-Type is a good indicator of intent from user + elif content_type and content_type.startswith("text/"): + request.set_text_body(content) + else: + try: + request.set_json_body(content) + except TypeError: + request.data = content + + if form_content: + request.set_formdata_body(form_content) + elif stream_content: + request.set_streamed_data_body(stream_content) + + return request + + def format_url(self, url_template: str, **kwargs: Any) -> str: + """Format request URL with the client base URL, unless the + supplied URL is already absolute. + + Note that both the base url and the template url can contain query parameters. + + :param str url_template: The request URL to be formatted if necessary. + :rtype: str + :return: The formatted URL. + """ + url = _format_url_section(url_template, **kwargs) + if url: + parsed = urlparse(url) + if not parsed.scheme or not parsed.netloc: + url = url.lstrip("/") + try: + base = self._base_url.format(**kwargs).rstrip("/") + except KeyError as key: + err_msg = "The value provided for the url part {} was incorrect, and resulted in an invalid url" + raise ValueError(err_msg.format(key.args[0])) from key + + url = _urljoin(base, url) + else: + url = self._base_url.format(**kwargs) + return url + + def get( + self, + url: str, + params: Optional[Dict[str, str]] = None, + headers: Optional[Dict[str, str]] = None, + content: Any = None, + form_content: Optional[Dict[str, Any]] = None, + ) -> "HttpRequest": + """Create a GET request object. + + :param str url: The request URL. + :param dict params: Request URL parameters. + :param dict headers: Headers + :param content: The body content + :type content: bytes or str or dict + :param dict form_content: Form content + :return: An HttpRequest object + :rtype: ~azure.core.pipeline.transport.HttpRequest + """ + request = self._request("GET", url, params, headers, content, form_content, None) + request.method = "GET" + return request + + def put( + self, + url: str, + params: Optional[Dict[str, str]] = None, + headers: Optional[Dict[str, str]] = None, + content: Any = None, + form_content: Optional[Dict[str, Any]] = None, + stream_content: Any = None, + ) -> HttpRequest: + """Create a PUT request object. + + :param str url: The request URL. + :param dict params: Request URL parameters. + :param dict headers: Headers + :param content: The body content + :type content: bytes or str or dict + :param dict form_content: Form content + :param stream_content: The body content as a stream + :type stream_content: stream or generator or asyncgenerator + :return: An HttpRequest object + :rtype: ~azure.core.pipeline.transport.HttpRequest + """ + request = self._request("PUT", url, params, headers, content, form_content, stream_content) + return request + + def post( + self, + url: str, + params: Optional[Dict[str, str]] = None, + headers: Optional[Dict[str, str]] = None, + content: Any = None, + form_content: Optional[Dict[str, Any]] = None, + stream_content: Any = None, + ) -> HttpRequest: + """Create a POST request object. + + :param str url: The request URL. + :param dict params: Request URL parameters. + :param dict headers: Headers + :param content: The body content + :type content: bytes or str or dict + :param dict form_content: Form content + :param stream_content: The body content as a stream + :type stream_content: stream or generator or asyncgenerator + :return: An HttpRequest object + :rtype: ~azure.core.pipeline.transport.HttpRequest + """ + request = self._request("POST", url, params, headers, content, form_content, stream_content) + return request + + def head( + self, + url: str, + params: Optional[Dict[str, str]] = None, + headers: Optional[Dict[str, str]] = None, + content: Any = None, + form_content: Optional[Dict[str, Any]] = None, + stream_content: Any = None, + ) -> HttpRequest: + """Create a HEAD request object. + + :param str url: The request URL. + :param dict params: Request URL parameters. + :param dict headers: Headers + :param content: The body content + :type content: bytes or str or dict + :param dict form_content: Form content + :param stream_content: The body content as a stream + :type stream_content: stream or generator or asyncgenerator + :return: An HttpRequest object + :rtype: ~azure.core.pipeline.transport.HttpRequest + """ + request = self._request("HEAD", url, params, headers, content, form_content, stream_content) + return request + + def patch( + self, + url: str, + params: Optional[Dict[str, str]] = None, + headers: Optional[Dict[str, str]] = None, + content: Any = None, + form_content: Optional[Dict[str, Any]] = None, + stream_content: Any = None, + ) -> HttpRequest: + """Create a PATCH request object. + + :param str url: The request URL. + :param dict params: Request URL parameters. + :param dict headers: Headers + :param content: The body content + :type content: bytes or str or dict + :param dict form_content: Form content + :param stream_content: The body content as a stream + :type stream_content: stream or generator or asyncgenerator + :return: An HttpRequest object + :rtype: ~azure.core.pipeline.transport.HttpRequest + """ + request = self._request("PATCH", url, params, headers, content, form_content, stream_content) + return request + + def delete( + self, + url: str, + params: Optional[Dict[str, str]] = None, + headers: Optional[Dict[str, str]] = None, + content: Any = None, + form_content: Optional[Dict[str, Any]] = None, + ) -> HttpRequest: + """Create a DELETE request object. + + :param str url: The request URL. + :param dict params: Request URL parameters. + :param dict headers: Headers + :param content: The body content + :type content: bytes or str or dict + :param dict form_content: Form content + :return: An HttpRequest object + :rtype: ~azure.core.pipeline.transport.HttpRequest + """ + request = self._request("DELETE", url, params, headers, content, form_content, None) + return request + + def merge( + self, + url: str, + params: Optional[Dict[str, str]] = None, + headers: Optional[Dict[str, str]] = None, + content: Any = None, + form_content: Optional[Dict[str, Any]] = None, + ) -> HttpRequest: + """Create a MERGE request object. + + :param str url: The request URL. + :param dict params: Request URL parameters. + :param dict headers: Headers + :param content: The body content + :type content: bytes or str or dict + :param dict form_content: Form content + :return: An HttpRequest object + :rtype: ~azure.core.pipeline.transport.HttpRequest + """ + request = self._request("MERGE", url, params, headers, content, form_content, None) + return request + + def options( + self, # pylint: disable=unused-argument + url: str, + params: Optional[Dict[str, str]] = None, + headers: Optional[Dict[str, str]] = None, + *, + content: Optional[Union[bytes, str, Dict[Any, Any]]] = None, + form_content: Optional[Dict[Any, Any]] = None, + **kwargs: Any, + ) -> HttpRequest: + """Create a OPTIONS request object. + + :param str url: The request URL. + :param dict params: Request URL parameters. + :param dict headers: Headers + :keyword content: The body content + :type content: bytes or str or dict + :keyword dict form_content: Form content + :return: An HttpRequest object + :rtype: ~azure.core.pipeline.transport.HttpRequest + """ + request = self._request("OPTIONS", url, params, headers, content, form_content, None) + return request diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_base_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_base_async.py new file mode 100644 index 0000000000000000000000000000000000000000..ab680a1e0b5e8d1033b9806911c0c3774a9c92e3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_base_async.py @@ -0,0 +1,169 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from __future__ import annotations +import asyncio +import abc +from collections.abc import AsyncIterator +from typing import ( + AsyncIterator as AsyncIteratorType, + TypeVar, + Generic, + Any, + AsyncContextManager, + Optional, + Type, + TYPE_CHECKING, +) +from types import TracebackType + +from ._base import _HttpResponseBase, _HttpClientTransportResponse, HttpRequest +from ...utils._pipeline_transport_rest_shared_async import _PartGenerator + + +AsyncHTTPResponseType = TypeVar("AsyncHTTPResponseType") +HTTPResponseType = TypeVar("HTTPResponseType") +HTTPRequestType = TypeVar("HTTPRequestType") + +if TYPE_CHECKING: + # We need a transport to define a pipeline, this "if" avoid a circular import + from .._base_async import AsyncPipeline + + +class _ResponseStopIteration(Exception): + pass + + +def _iterate_response_content(iterator): + """To avoid the following error from Python: + > TypeError: StopIteration interacts badly with generators and cannot be raised into a Future + + :param iterator: An iterator + :type iterator: iterator + :return: The next item in the iterator + :rtype: any + """ + try: + return next(iterator) + except StopIteration: + raise _ResponseStopIteration() # pylint: disable=raise-missing-from + + +class AsyncHttpResponse(_HttpResponseBase, AsyncContextManager["AsyncHttpResponse"]): # pylint: disable=abstract-method + """An AsyncHttpResponse ABC. + + Allows for the asynchronous streaming of data from the response. + """ + + def stream_download( + self, pipeline: AsyncPipeline[HttpRequest, "AsyncHttpResponse"], *, decompress: bool = True, **kwargs: Any + ) -> AsyncIteratorType[bytes]: + """Generator for streaming response body data. + + Should be implemented by sub-classes if streaming download + is supported. Will return an asynchronous generator. + + :param pipeline: The pipeline object + :type pipeline: azure.core.pipeline.Pipeline + :keyword bool decompress: If True which is default, will attempt to decode the body based + on the *content-encoding* header. + :return: An async iterator of bytes + :rtype: AsyncIterator[bytes] + """ + raise NotImplementedError("stream_download is not implemented.") + + def parts(self) -> AsyncIterator["AsyncHttpResponse"]: + """Assuming the content-type is multipart/mixed, will return the parts as an async iterator. + + :return: An async iterator of the parts + :rtype: AsyncIterator + :raises ValueError: If the content is not multipart/mixed + """ + if not self.content_type or not self.content_type.startswith("multipart/mixed"): + raise ValueError("You can't get parts if the response is not multipart/mixed") + + return _PartGenerator(self, default_http_response_type=AsyncHttpClientTransportResponse) + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ) -> None: + return None + + +class AsyncHttpClientTransportResponse( # pylint: disable=abstract-method + _HttpClientTransportResponse, AsyncHttpResponse +): + """Create a HTTPResponse from an http.client response. + + Body will NOT be read by the constructor. Call "body()" to load the body in memory if necessary. + + :param HttpRequest request: The request. + :param httpclient_response: The object returned from an HTTP(S)Connection from http.client + """ + + +class AsyncHttpTransport( + AsyncContextManager["AsyncHttpTransport"], + abc.ABC, + Generic[HTTPRequestType, AsyncHTTPResponseType], +): + """An http sender ABC.""" + + @abc.abstractmethod + async def send(self, request: HTTPRequestType, **kwargs: Any) -> AsyncHTTPResponseType: + """Send the request using this HTTP sender. + + :param request: The request object. Exact type can be inferred from the pipeline. + :type request: any + :return: The response object. Exact type can be inferred from the pipeline. + :rtype: any + """ + + @abc.abstractmethod + async def open(self) -> None: + """Assign new session if one does not already exist.""" + + @abc.abstractmethod + async def close(self) -> None: + """Close the session if it is not externally owned.""" + + async def sleep(self, duration: float) -> None: + """Sleep for the specified duration. + + You should always ask the transport to sleep, and not call directly + the stdlib. This is mostly important in async, as the transport + may not use asyncio but other implementation like trio and they their own + way to sleep, but to keep design + consistent, it's cleaner to always ask the transport to sleep and let the transport + implementor decide how to do it. + By default, this method will use "asyncio", and don't need to be overridden + if your transport does too. + + :param float duration: The number of seconds to sleep. + """ + await asyncio.sleep(duration) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_base_requests_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_base_requests_async.py new file mode 100644 index 0000000000000000000000000000000000000000..15ec81a881fa873723306c7ddb2b621af1167288 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_base_requests_async.py @@ -0,0 +1,55 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from typing import Optional, Type +from types import TracebackType +from ._requests_basic import RequestsTransport +from ._base_async import AsyncHttpTransport + + +class RequestsAsyncTransportBase(RequestsTransport, AsyncHttpTransport): # type: ignore + async def _retrieve_request_data(self, request): + if hasattr(request.data, "__aiter__"): + # Need to consume that async generator, since requests can't do anything with it + # That's not ideal, but a list is our only choice. Memory not optimal here, + # but providing an async generator to a requests based transport is not optimal too + new_data = [] + async for part in request.data: + new_data.append(part) + data_to_send = iter(new_data) + else: + data_to_send = request.data + return data_to_send + + async def __aenter__(self): + return super(RequestsAsyncTransportBase, self).__enter__() + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ): + return super(RequestsAsyncTransportBase, self).__exit__(exc_type, exc_value, traceback) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_bigger_block_size_http_adapters.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_bigger_block_size_http_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..d2096773c00f42bbcfd72afdd6f546ea372f2c00 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_bigger_block_size_http_adapters.py @@ -0,0 +1,48 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +import sys +from requests.adapters import HTTPAdapter + + +class BiggerBlockSizeHTTPAdapter(HTTPAdapter): + def get_connection(self, url, proxies=None): + """Returns a urllib3 connection for the given URL. This should not be + called from user code, and is only exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param str url: The URL to connect to. + :param MutableMapping proxies: (optional) A Requests-style dictionary of proxies used on this request. + :rtype: urllib3.ConnectionPool + :returns: The urllib3 ConnectionPool for the given URL. + """ + conn = super(BiggerBlockSizeHTTPAdapter, self).get_connection(url, proxies) + system_version = tuple(sys.version_info)[:3] + if system_version[:2] >= (3, 7): + if not conn.conn_kw: + conn.conn_kw = {} + conn.conn_kw["blocksize"] = 32768 + return conn diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_requests_asyncio.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_requests_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..5b51e42015db386b234725354406fc2f09dc5fac --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_requests_asyncio.py @@ -0,0 +1,297 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import asyncio +from collections.abc import AsyncIterator +import functools +import logging +from typing import ( + Any, + Optional, + AsyncIterator as AsyncIteratorType, + Union, + TYPE_CHECKING, + overload, + Type, + MutableMapping, +) +from types import TracebackType +from urllib3.exceptions import ( + ProtocolError, + NewConnectionError, + ConnectTimeoutError, +) +import requests + +from azure.core.exceptions import ( + ServiceRequestError, + ServiceResponseError, + IncompleteReadError, + HttpResponseError, +) +from azure.core.pipeline import Pipeline +from ._base import HttpRequest +from ._base_async import ( + AsyncHttpResponse, + _ResponseStopIteration, + _iterate_response_content, +) +from ._requests_basic import ( + RequestsTransportResponse, + _read_raw_stream, + AzureErrorUnion, +) +from ._base_requests_async import RequestsAsyncTransportBase +from .._tools import is_rest as _is_rest +from .._tools_async import ( + handle_no_stream_rest_response as _handle_no_stream_rest_response, +) + +if TYPE_CHECKING: + from ...rest import ( + HttpRequest as RestHttpRequest, + AsyncHttpResponse as RestAsyncHttpResponse, + ) + +_LOGGER = logging.getLogger(__name__) + + +def _get_running_loop(): + return asyncio.get_running_loop() + + +# pylint: disable=too-many-ancestors +class AsyncioRequestsTransport(RequestsAsyncTransportBase): + """Identical implementation as the synchronous RequestsTransport wrapped in a class with + asynchronous methods. Uses the built-in asyncio event loop. + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_async.py + :start-after: [START asyncio] + :end-before: [END asyncio] + :language: python + :dedent: 4 + :caption: Asynchronous transport with asyncio. + """ + + async def __aenter__(self): + return super(AsyncioRequestsTransport, self).__enter__() + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ) -> None: + return super(AsyncioRequestsTransport, self).__exit__(exc_type, exc_value, traceback) + + async def sleep(self, duration): # pylint:disable=invalid-overridden-method + await asyncio.sleep(duration) + + @overload # type: ignore + async def send( # pylint:disable=invalid-overridden-method + self, request: HttpRequest, *, proxies: Optional[MutableMapping[str, str]] = None, **kwargs: Any + ) -> AsyncHttpResponse: + """Send the request using this HTTP sender. + + :param request: The HttpRequest + :type request: ~azure.core.pipeline.transport.HttpRequest + :return: The AsyncHttpResponse + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + + :keyword MutableMapping proxies: will define the proxy to use. Proxy is a dict (protocol, url) + """ + + @overload + async def send( # pylint:disable=invalid-overridden-method + self, request: "RestHttpRequest", *, proxies: Optional[MutableMapping[str, str]] = None, **kwargs: Any + ) -> "RestAsyncHttpResponse": + """Send a `azure.core.rest` request using this HTTP sender. + + :param request: The HttpRequest + :type request: ~azure.core.rest.HttpRequest + :return: The AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse + + :keyword MutableMapping proxies: will define the proxy to use. Proxy is a dict (protocol, url) + """ + + async def send( # pylint:disable=invalid-overridden-method + self, + request: Union[HttpRequest, "RestHttpRequest"], + *, + proxies: Optional[MutableMapping[str, str]] = None, + **kwargs + ) -> Union[AsyncHttpResponse, "RestAsyncHttpResponse"]: + """Send the request using this HTTP sender. + + :param request: The HttpRequest + :type request: ~azure.core.pipeline.transport.HttpRequest + :return: The AsyncHttpResponse + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + + :keyword MutableMapping proxies: will define the proxy to use. Proxy is a dict (protocol, url) + """ + self.open() + loop = kwargs.get("loop", _get_running_loop()) + response = None + error: Optional[AzureErrorUnion] = None + data_to_send = await self._retrieve_request_data(request) + try: + response = await loop.run_in_executor( + None, + functools.partial( + self.session.request, + request.method, + request.url, + headers=request.headers, + data=data_to_send, + files=request.files, + verify=kwargs.pop("connection_verify", self.connection_config.verify), + timeout=kwargs.pop("connection_timeout", self.connection_config.timeout), + cert=kwargs.pop("connection_cert", self.connection_config.cert), + allow_redirects=False, + proxies=proxies, + **kwargs + ), + ) + response.raw.enforce_content_length = True + + except ( + NewConnectionError, + ConnectTimeoutError, + ) as err: + error = ServiceRequestError(err, error=err) + except requests.exceptions.ReadTimeout as err: + error = ServiceResponseError(err, error=err) + except requests.exceptions.ConnectionError as err: + if err.args and isinstance(err.args[0], ProtocolError): + error = ServiceResponseError(err, error=err) + else: + error = ServiceRequestError(err, error=err) + except requests.exceptions.ChunkedEncodingError as err: + msg = err.__str__() + if "IncompleteRead" in msg: + _LOGGER.warning("Incomplete download: %s", err) + error = IncompleteReadError(err, error=err) + else: + _LOGGER.warning("Unable to stream download: %s", err) + error = HttpResponseError(err, error=err) + except requests.RequestException as err: + error = ServiceRequestError(err, error=err) + + if error: + raise error + if _is_rest(request): + from azure.core.rest._requests_asyncio import ( + RestAsyncioRequestsTransportResponse, + ) + + retval = RestAsyncioRequestsTransportResponse( + request=request, + internal_response=response, + block_size=self.connection_config.data_block_size, + ) + if not kwargs.get("stream"): + await _handle_no_stream_rest_response(retval) + return retval + + return AsyncioRequestsTransportResponse(request, response, self.connection_config.data_block_size) + + +class AsyncioStreamDownloadGenerator(AsyncIterator): + """Streams the response body data. + + :param pipeline: The pipeline object + :type pipeline: ~azure.core.pipeline.AsyncPipeline + :param response: The response object. + :type response: ~azure.core.pipeline.transport.AsyncHttpResponse + :keyword bool decompress: If True which is default, will attempt to decode the body based + on the *content-encoding* header. + """ + + def __init__(self, pipeline: Pipeline, response: AsyncHttpResponse, **kwargs) -> None: + self.pipeline = pipeline + self.request = response.request + self.response = response + self.block_size = response.block_size + decompress = kwargs.pop("decompress", True) + if len(kwargs) > 0: + raise TypeError("Got an unexpected keyword argument: {}".format(list(kwargs.keys())[0])) + internal_response = response.internal_response + if decompress: + self.iter_content_func = internal_response.iter_content(self.block_size) + else: + self.iter_content_func = _read_raw_stream(internal_response, self.block_size) + self.content_length = int(response.headers.get("Content-Length", 0)) + + def __len__(self): + return self.content_length + + async def __anext__(self): + loop = _get_running_loop() + internal_response = self.response.internal_response + try: + chunk = await loop.run_in_executor( + None, + _iterate_response_content, + self.iter_content_func, + ) + if not chunk: + raise _ResponseStopIteration() + return chunk + except _ResponseStopIteration: + internal_response.close() + raise StopAsyncIteration() # pylint: disable=raise-missing-from + except requests.exceptions.StreamConsumedError: + raise + except requests.exceptions.ChunkedEncodingError as err: + msg = err.__str__() + if "IncompleteRead" in msg: + _LOGGER.warning("Incomplete download: %s", err) + internal_response.close() + raise IncompleteReadError(err, error=err) from err + _LOGGER.warning("Unable to stream download: %s", err) + internal_response.close() + raise HttpResponseError(err, error=err) from err + except Exception as err: + _LOGGER.warning("Unable to stream download: %s", err) + internal_response.close() + raise + + +class AsyncioRequestsTransportResponse(AsyncHttpResponse, RequestsTransportResponse): # type: ignore + """Asynchronous streaming of data from the response.""" + + def stream_download(self, pipeline, **kwargs) -> AsyncIteratorType[bytes]: # type: ignore + """Generator for streaming request body data. + + :param pipeline: The pipeline object + :type pipeline: ~azure.core.pipeline.AsyncPipeline + :rtype: AsyncIterator[bytes] + :return: An async iterator of bytes chunks + """ + return AsyncioStreamDownloadGenerator(pipeline, self, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_requests_basic.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_requests_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..0a3b2495d0e03fe9a543a417f5cbac97973bead8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_requests_basic.py @@ -0,0 +1,398 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import logging +from typing import Iterator, Optional, Union, TypeVar, overload, cast, TYPE_CHECKING, MutableMapping +from urllib3.util.retry import Retry +from urllib3.exceptions import ( + DecodeError as CoreDecodeError, + ReadTimeoutError, + ProtocolError, + NewConnectionError, + ConnectTimeoutError, +) +import requests + +from azure.core.configuration import ConnectionConfiguration +from azure.core.exceptions import ( + ServiceRequestError, + ServiceResponseError, + IncompleteReadError, + HttpResponseError, + DecodeError, +) +from . import HttpRequest # pylint: disable=unused-import + +from ._base import HttpTransport, HttpResponse, _HttpResponseBase +from ._bigger_block_size_http_adapters import BiggerBlockSizeHTTPAdapter +from .._tools import ( + is_rest as _is_rest, + handle_non_stream_rest_response as _handle_non_stream_rest_response, +) + +if TYPE_CHECKING: + from ...rest import HttpRequest as RestHttpRequest, HttpResponse as RestHttpResponse + +AzureErrorUnion = Union[ + ServiceRequestError, + ServiceResponseError, + IncompleteReadError, + HttpResponseError, +] + +PipelineType = TypeVar("PipelineType") + +_LOGGER = logging.getLogger(__name__) + + +def _read_raw_stream(response, chunk_size=1): + # Special case for urllib3. + if hasattr(response.raw, "stream"): + try: + for chunk in response.raw.stream(chunk_size, decode_content=False): + yield chunk + except ProtocolError as e: + raise ServiceResponseError(e, error=e) from e + except CoreDecodeError as e: + raise DecodeError(e, error=e) from e + except ReadTimeoutError as e: + raise ServiceRequestError(e, error=e) from e + else: + # Standard file-like object. + while True: + chunk = response.raw.read(chunk_size) + if not chunk: + break + yield chunk + + # following behavior from requests iter_content, we set content consumed to True + # https://github.com/psf/requests/blob/master/requests/models.py#L774 + response._content_consumed = True # pylint: disable=protected-access + + +class _RequestsTransportResponseBase(_HttpResponseBase): + """Base class for accessing response data. + + :param HttpRequest request: The request. + :param requests_response: The object returned from the HTTP library. + :type requests_response: requests.Response + :param int block_size: Size in bytes. + """ + + def __init__(self, request, requests_response, block_size=None): + super(_RequestsTransportResponseBase, self).__init__(request, requests_response, block_size=block_size) + self.status_code = requests_response.status_code + self.headers = requests_response.headers + self.reason = requests_response.reason + self.content_type = requests_response.headers.get("content-type") + + def body(self): + return self.internal_response.content + + def text(self, encoding: Optional[str] = None) -> str: + """Return the whole body as a string. + + If encoding is not provided, mostly rely on requests auto-detection, except + for BOM, that requests ignores. If we see a UTF8 BOM, we assumes UTF8 unlike requests. + + :param str encoding: The encoding to apply. + :rtype: str + :return: The body as text. + """ + if not encoding: + # There is a few situation where "requests" magic doesn't fit us: + # - https://github.com/psf/requests/issues/654 + # - https://github.com/psf/requests/issues/1737 + # - https://github.com/psf/requests/issues/2086 + from codecs import BOM_UTF8 + + if self.internal_response.content[:3] == BOM_UTF8: + encoding = "utf-8-sig" + + if encoding: + if encoding == "utf-8": + encoding = "utf-8-sig" + + self.internal_response.encoding = encoding + + return self.internal_response.text + + +class StreamDownloadGenerator: + """Generator for streaming response data. + + :param pipeline: The pipeline object + :type pipeline: ~azure.core.pipeline.Pipeline + :param response: The response object. + :type response: ~azure.core.pipeline.transport.HttpResponse + :keyword bool decompress: If True which is default, will attempt to decode the body based + on the *content-encoding* header. + """ + + def __init__(self, pipeline, response, **kwargs): + self.pipeline = pipeline + self.request = response.request + self.response = response + self.block_size = response.block_size + decompress = kwargs.pop("decompress", True) + if len(kwargs) > 0: + raise TypeError("Got an unexpected keyword argument: {}".format(list(kwargs.keys())[0])) + internal_response = response.internal_response + if decompress: + self.iter_content_func = internal_response.iter_content(self.block_size) + else: + self.iter_content_func = _read_raw_stream(internal_response, self.block_size) + self.content_length = int(response.headers.get("Content-Length", 0)) + + def __len__(self): + return self.content_length + + def __iter__(self): + return self + + def __next__(self): + internal_response = self.response.internal_response + try: + chunk = next(self.iter_content_func) + if not chunk: + raise StopIteration() + return chunk + except StopIteration: + internal_response.close() + raise StopIteration() # pylint: disable=raise-missing-from + except requests.exceptions.StreamConsumedError: + raise + except requests.exceptions.ContentDecodingError as err: + raise DecodeError(err, error=err) from err + except requests.exceptions.ChunkedEncodingError as err: + msg = err.__str__() + if "IncompleteRead" in msg: + _LOGGER.warning("Incomplete download: %s", err) + internal_response.close() + raise IncompleteReadError(err, error=err) from err + _LOGGER.warning("Unable to stream download: %s", err) + internal_response.close() + raise HttpResponseError(err, error=err) from err + except Exception as err: + _LOGGER.warning("Unable to stream download: %s", err) + internal_response.close() + raise + + next = __next__ # Python 2 compatibility. + + +class RequestsTransportResponse(HttpResponse, _RequestsTransportResponseBase): + """Streaming of data from the response.""" + + def stream_download(self, pipeline: PipelineType, **kwargs) -> Iterator[bytes]: + """Generator for streaming request body data. + + :param pipeline: The pipeline object + :type pipeline: ~azure.core.pipeline.Pipeline + :rtype: iterator[bytes] + :return: The stream of data + """ + return StreamDownloadGenerator(pipeline, self, **kwargs) + + +class RequestsTransport(HttpTransport): + """Implements a basic requests HTTP sender. + + Since requests team recommends to use one session per requests, you should + not consider this class as thread-safe, since it will use one Session + per instance. + + In this simple implementation: + - You provide the configured session if you want to, or a basic session is created. + - All kwargs received by "send" are sent to session.request directly + + :keyword requests.Session session: Request session to use instead of the default one. + :keyword bool session_owner: Decide if the session provided by user is owned by this transport. Default to True. + :keyword bool use_env_settings: Uses proxy settings from environment. Defaults to True. + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_sync.py + :start-after: [START requests] + :end-before: [END requests] + :language: python + :dedent: 4 + :caption: Synchronous transport with Requests. + """ + + _protocols = ["http://", "https://"] + + def __init__(self, **kwargs) -> None: + self.session = kwargs.get("session", None) + self._session_owner = kwargs.get("session_owner", True) + if not self._session_owner and not self.session: + raise ValueError("session_owner cannot be False if no session is provided") + self.connection_config = ConnectionConfiguration(**kwargs) + self._use_env_settings = kwargs.pop("use_env_settings", True) + + def __enter__(self) -> "RequestsTransport": + self.open() + return self + + def __exit__(self, *args): # pylint: disable=arguments-differ + self.close() + + def _init_session(self, session: requests.Session) -> None: + """Init session level configuration of requests. + + This is initialization I want to do once only on a session. + + :param requests.Session session: The session object. + """ + session.trust_env = self._use_env_settings + disable_retries = Retry(total=False, redirect=False, raise_on_status=False) + adapter = BiggerBlockSizeHTTPAdapter(max_retries=disable_retries) + for p in self._protocols: + session.mount(p, adapter) + + def open(self): + if not self.session and self._session_owner: + self.session = requests.Session() + self._init_session(self.session) + # pyright has trouble to understand that self.session is not None, since we raised at worst in the init + self.session = cast(requests.Session, self.session) + + def close(self): + if self._session_owner and self.session: + self.session.close() + self._session_owner = False + self.session = None + + @overload + def send( + self, request: HttpRequest, *, proxies: Optional[MutableMapping[str, str]] = None, **kwargs + ) -> HttpResponse: + """Send a rest request and get back a rest response. + + :param request: The request object to be sent. + :type request: ~azure.core.pipeline.transport.HttpRequest + :return: An HTTPResponse object. + :rtype: ~azure.core.pipeline.transport.HttpResponse + + :keyword MutableMapping proxies: will define the proxy to use. Proxy is a dict (protocol, url) + """ + + @overload + def send( + self, request: "RestHttpRequest", *, proxies: Optional[MutableMapping[str, str]] = None, **kwargs + ) -> "RestHttpResponse": + """Send an `azure.core.rest` request and get back a rest response. + + :param request: The request object to be sent. + :type request: ~azure.core.rest.HttpRequest + :return: An HTTPResponse object. + :rtype: ~azure.core.rest.HttpResponse + + :keyword MutableMapping proxies: will define the proxy to use. Proxy is a dict (protocol, url) + """ + + def send( + self, + request: Union[HttpRequest, "RestHttpRequest"], + *, + proxies: Optional[MutableMapping[str, str]] = None, + **kwargs + ) -> Union[HttpResponse, "RestHttpResponse"]: + """Send request object according to configuration. + + :param request: The request object to be sent. + :type request: ~azure.core.pipeline.transport.HttpRequest + :return: An HTTPResponse object. + :rtype: ~azure.core.pipeline.transport.HttpResponse + + :keyword MutableMapping proxies: will define the proxy to use. Proxy is a dict (protocol, url) + """ + self.open() + response = None + error: Optional[AzureErrorUnion] = None + + try: + connection_timeout = kwargs.pop("connection_timeout", self.connection_config.timeout) + + if isinstance(connection_timeout, tuple): + if "read_timeout" in kwargs: + raise ValueError("Cannot set tuple connection_timeout and read_timeout together") + _LOGGER.warning("Tuple timeout setting is deprecated") + timeout = connection_timeout + else: + read_timeout = kwargs.pop("read_timeout", self.connection_config.read_timeout) + timeout = (connection_timeout, read_timeout) + response = self.session.request( # type: ignore + request.method, + request.url, + headers=request.headers, + data=request.data, + files=request.files, + verify=kwargs.pop("connection_verify", self.connection_config.verify), + timeout=timeout, + cert=kwargs.pop("connection_cert", self.connection_config.cert), + allow_redirects=False, + proxies=proxies, + **kwargs + ) + response.raw.enforce_content_length = True + + except ( + NewConnectionError, + ConnectTimeoutError, + ) as err: + error = ServiceRequestError(err, error=err) + except requests.exceptions.ReadTimeout as err: + error = ServiceResponseError(err, error=err) + except requests.exceptions.ConnectionError as err: + if err.args and isinstance(err.args[0], ProtocolError): + error = ServiceResponseError(err, error=err) + else: + error = ServiceRequestError(err, error=err) + except requests.exceptions.ChunkedEncodingError as err: + msg = err.__str__() + if "IncompleteRead" in msg: + _LOGGER.warning("Incomplete download: %s", err) + error = IncompleteReadError(err, error=err) + else: + _LOGGER.warning("Unable to stream download: %s", err) + error = HttpResponseError(err, error=err) + except requests.RequestException as err: + error = ServiceRequestError(err, error=err) + + if error: + raise error + if _is_rest(request): + from azure.core.rest._requests_basic import RestRequestsTransportResponse + + retval: RestHttpResponse = RestRequestsTransportResponse( + request=request, + internal_response=response, + block_size=self.connection_config.data_block_size, + ) + if not kwargs.get("stream"): + _handle_non_stream_rest_response(retval) + return retval + return RequestsTransportResponse(request, response, self.connection_config.data_block_size) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_requests_trio.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_requests_trio.py new file mode 100644 index 0000000000000000000000000000000000000000..a4a3337719d9430ff97a3de01d8998a331b5fd85 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/pipeline/transport/_requests_trio.py @@ -0,0 +1,303 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from collections.abc import AsyncIterator +import functools +import logging +from typing import Any, Optional, AsyncIterator as AsyncIteratorType, TYPE_CHECKING, overload, Type, MutableMapping +from types import TracebackType +from urllib3.exceptions import ( + ProtocolError, + NewConnectionError, + ConnectTimeoutError, +) + +import trio + +import requests + +from azure.core.exceptions import ( + ServiceRequestError, + ServiceResponseError, + IncompleteReadError, + HttpResponseError, +) +from azure.core.pipeline import Pipeline +from ._base import HttpRequest +from ._base_async import ( + AsyncHttpResponse, + _ResponseStopIteration, + _iterate_response_content, +) +from ._requests_basic import ( + RequestsTransportResponse, + _read_raw_stream, + AzureErrorUnion, +) +from ._base_requests_async import RequestsAsyncTransportBase +from .._tools import is_rest as _is_rest +from .._tools_async import ( + handle_no_stream_rest_response as _handle_no_stream_rest_response, +) + +if TYPE_CHECKING: + from ...rest import ( + HttpRequest as RestHttpRequest, + AsyncHttpResponse as RestAsyncHttpResponse, + ) + + +_LOGGER = logging.getLogger(__name__) + + +class TrioStreamDownloadGenerator(AsyncIterator): + """Generator for streaming response data. + + :param pipeline: The pipeline object + :type pipeline: ~azure.core.pipeline.AsyncPipeline + :param response: The response object. + :type response: ~azure.core.pipeline.transport.AsyncHttpResponse + :keyword bool decompress: If True which is default, will attempt to decode the body based + on the *content-encoding* header. + """ + + def __init__(self, pipeline: Pipeline, response: AsyncHttpResponse, **kwargs) -> None: + self.pipeline = pipeline + self.request = response.request + self.response = response + self.block_size = response.block_size + decompress = kwargs.pop("decompress", True) + if len(kwargs) > 0: + raise TypeError("Got an unexpected keyword argument: {}".format(list(kwargs.keys())[0])) + internal_response = response.internal_response + if decompress: + self.iter_content_func = internal_response.iter_content(self.block_size) + else: + self.iter_content_func = _read_raw_stream(internal_response, self.block_size) + self.content_length = int(response.headers.get("Content-Length", 0)) + + def __len__(self): + return self.content_length + + async def __anext__(self): + internal_response = self.response.internal_response + try: + try: + chunk = await trio.to_thread.run_sync( + _iterate_response_content, + self.iter_content_func, + ) + except AttributeError: # trio < 0.12.1 + chunk = await trio.run_sync_in_worker_thread( # type: ignore # pylint: disable=no-member + _iterate_response_content, + self.iter_content_func, + ) + if not chunk: + raise _ResponseStopIteration() + return chunk + except _ResponseStopIteration: + internal_response.close() + raise StopAsyncIteration() # pylint: disable=raise-missing-from + except requests.exceptions.StreamConsumedError: + raise + except requests.exceptions.ChunkedEncodingError as err: + msg = err.__str__() + if "IncompleteRead" in msg: + _LOGGER.warning("Incomplete download: %s", err) + internal_response.close() + raise IncompleteReadError(err, error=err) from err + _LOGGER.warning("Unable to stream download: %s", err) + internal_response.close() + raise HttpResponseError(err, error=err) from err + except Exception as err: + _LOGGER.warning("Unable to stream download: %s", err) + internal_response.close() + raise + + +class TrioRequestsTransportResponse(AsyncHttpResponse, RequestsTransportResponse): # type: ignore + """Asynchronous streaming of data from the response.""" + + def stream_download(self, pipeline, **kwargs) -> AsyncIteratorType[bytes]: # type: ignore + """Generator for streaming response data. + + :param pipeline: The pipeline object + :type pipeline: ~azure.core.pipeline.AsyncPipeline + :rtype: AsyncIterator[bytes] + :return: An async iterator of bytes chunks + """ + return TrioStreamDownloadGenerator(pipeline, self, **kwargs) + + +class TrioRequestsTransport(RequestsAsyncTransportBase): + """Identical implementation as the synchronous RequestsTransport wrapped in a class with + asynchronous methods. Uses the third party trio event loop. + + .. admonition:: Example: + + .. literalinclude:: ../samples/test_example_async.py + :start-after: [START trio] + :end-before: [END trio] + :language: python + :dedent: 4 + :caption: Asynchronous transport with trio. + """ + + async def __aenter__(self): + return super(TrioRequestsTransport, self).__enter__() + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ) -> None: + return super(TrioRequestsTransport, self).__exit__(exc_type, exc_value, traceback) + + async def sleep(self, duration): # pylint:disable=invalid-overridden-method + await trio.sleep(duration) + + @overload # type: ignore + async def send( # pylint:disable=invalid-overridden-method + self, request: HttpRequest, *, proxies: Optional[MutableMapping[str, str]] = None, **kwargs: Any + ) -> AsyncHttpResponse: + """Send the request using this HTTP sender. + + :param request: The HttpRequest + :type request: ~azure.core.pipeline.transport.HttpRequest + :return: The AsyncHttpResponse + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + + :keyword MutableMapping proxies: will define the proxy to use. Proxy is a dict (protocol, url) + """ + + @overload + async def send( # pylint:disable=invalid-overridden-method + self, request: "RestHttpRequest", *, proxies: Optional[MutableMapping[str, str]] = None, **kwargs: Any + ) -> "RestAsyncHttpResponse": + """Send an `azure.core.rest` request using this HTTP sender. + + :param request: The HttpRequest + :type request: ~azure.core.rest.HttpRequest + :return: The AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse + + :keyword MutableMapping proxies: will define the proxy to use. Proxy is a dict (protocol, url) + """ + + async def send( + self, request, *, proxies: Optional[MutableMapping[str, str]] = None, **kwargs: Any + ): # pylint:disable=invalid-overridden-method + """Send the request using this HTTP sender. + + :param request: The HttpRequest + :type request: ~azure.core.pipeline.transport.HttpRequest + :return: The AsyncHttpResponse + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + + :keyword MutableMapping proxies: will define the proxy to use. Proxy is a dict (protocol, url) + """ + self.open() + trio_limiter = kwargs.get("trio_limiter", None) + response = None + error: Optional[AzureErrorUnion] = None + data_to_send = await self._retrieve_request_data(request) + try: + try: + response = await trio.to_thread.run_sync( + functools.partial( + self.session.request, + request.method, + request.url, + headers=request.headers, + data=data_to_send, + files=request.files, + verify=kwargs.pop("connection_verify", self.connection_config.verify), + timeout=kwargs.pop("connection_timeout", self.connection_config.timeout), + cert=kwargs.pop("connection_cert", self.connection_config.cert), + allow_redirects=False, + proxies=proxies, + **kwargs + ), + limiter=trio_limiter, + ) + except AttributeError: # trio < 0.12.1 + response = await trio.run_sync_in_worker_thread( # type: ignore # pylint: disable=no-member + functools.partial( + self.session.request, + request.method, + request.url, + headers=request.headers, + data=request.data, + files=request.files, + verify=kwargs.pop("connection_verify", self.connection_config.verify), + timeout=kwargs.pop("connection_timeout", self.connection_config.timeout), + cert=kwargs.pop("connection_cert", self.connection_config.cert), + allow_redirects=False, + proxies=proxies, + **kwargs + ), + limiter=trio_limiter, + ) + response.raw.enforce_content_length = True + + except ( + NewConnectionError, + ConnectTimeoutError, + ) as err: + error = ServiceRequestError(err, error=err) + except requests.exceptions.ReadTimeout as err: + error = ServiceResponseError(err, error=err) + except requests.exceptions.ConnectionError as err: + if err.args and isinstance(err.args[0], ProtocolError): + error = ServiceResponseError(err, error=err) + else: + error = ServiceRequestError(err, error=err) + except requests.exceptions.ChunkedEncodingError as err: + msg = err.__str__() + if "IncompleteRead" in msg: + _LOGGER.warning("Incomplete download: %s", err) + error = IncompleteReadError(err, error=err) + else: + _LOGGER.warning("Unable to stream download: %s", err) + error = HttpResponseError(err, error=err) + except requests.RequestException as err: + error = ServiceRequestError(err, error=err) + + if error: + raise error + if _is_rest(request): + from azure.core.rest._requests_trio import RestTrioRequestsTransportResponse + + retval = RestTrioRequestsTransportResponse( + request=request, + internal_response=response, + block_size=self.connection_config.data_block_size, + ) + if not kwargs.get("stream"): + await _handle_no_stream_rest_response(retval) + return retval + + return TrioRequestsTransportResponse(request, response, self.connection_config.data_block_size) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..193e76faada5b9a3aeb97012b2506eabf92e0391 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/__init__.py @@ -0,0 +1,42 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from ._poller import LROPoller, NoPolling, PollingMethod +from ._async_poller import ( + AsyncNoPolling, + AsyncPollingMethod, + async_poller, + AsyncLROPoller, +) + +__all__ = [ + "LROPoller", + "NoPolling", + "PollingMethod", + "AsyncNoPolling", + "AsyncPollingMethod", + "async_poller", + "AsyncLROPoller", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/_async_poller.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/_async_poller.py new file mode 100644 index 0000000000000000000000000000000000000000..1dedb12ac1ad58fbc285e26869dfe5734cf40fe8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/_async_poller.py @@ -0,0 +1,208 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import logging +from typing import Callable, Any, Tuple, Generic, TypeVar, Generator, Awaitable + +from ..exceptions import AzureError +from ._poller import _SansIONoPolling + + +PollingReturnType_co = TypeVar("PollingReturnType_co", covariant=True) +DeserializationCallbackType = Any + +_LOGGER = logging.getLogger(__name__) + + +class AsyncPollingMethod(Generic[PollingReturnType_co]): + """ABC class for polling method.""" + + def initialize( + self, client: Any, initial_response: Any, deserialization_callback: DeserializationCallbackType + ) -> None: + raise NotImplementedError("This method needs to be implemented") + + async def run(self) -> None: + raise NotImplementedError("This method needs to be implemented") + + def status(self) -> str: + raise NotImplementedError("This method needs to be implemented") + + def finished(self) -> bool: + raise NotImplementedError("This method needs to be implemented") + + def resource(self) -> PollingReturnType_co: + raise NotImplementedError("This method needs to be implemented") + + def get_continuation_token(self) -> str: + raise TypeError("Polling method '{}' doesn't support get_continuation_token".format(self.__class__.__name__)) + + @classmethod + def from_continuation_token( + cls, continuation_token: str, **kwargs: Any + ) -> Tuple[Any, Any, DeserializationCallbackType]: + raise TypeError("Polling method '{}' doesn't support from_continuation_token".format(cls.__name__)) + + +class AsyncNoPolling(_SansIONoPolling[PollingReturnType_co], AsyncPollingMethod[PollingReturnType_co]): + """An empty async poller that returns the deserialized initial response.""" + + async def run(self) -> None: # pylint:disable=invalid-overridden-method + """Empty run, no polling. + Just override initial run to add "async" + """ + + +async def async_poller( + client: Any, + initial_response: Any, + deserialization_callback: Callable[[Any], PollingReturnType_co], + polling_method: AsyncPollingMethod[PollingReturnType_co], +) -> PollingReturnType_co: + """Async Poller for long running operations. + + .. deprecated:: 1.5.0 + Use :class:`AsyncLROPoller` instead. + + :param client: A pipeline service client. + :type client: ~azure.core.PipelineClient + :param initial_response: The initial call response + :type initial_response: ~azure.core.pipeline.PipelineResponse + :param deserialization_callback: A callback that takes a Response and return a deserialized object. + If a subclass of Model is given, this passes "deserialize" as callback. + :type deserialization_callback: callable or msrest.serialization.Model + :param polling_method: The polling strategy to adopt + :type polling_method: ~azure.core.polling.PollingMethod + :return: The final resource at the end of the polling. + :rtype: any or None + """ + poller = AsyncLROPoller(client, initial_response, deserialization_callback, polling_method) + return await poller + + +class AsyncLROPoller(Generic[PollingReturnType_co], Awaitable[PollingReturnType_co]): + """Async poller for long running operations. + + :param client: A pipeline service client + :type client: ~azure.core.PipelineClient + :param initial_response: The initial call response + :type initial_response: ~azure.core.pipeline.PipelineResponse + :param deserialization_callback: A callback that takes a Response and return a deserialized object. + If a subclass of Model is given, this passes "deserialize" as callback. + :type deserialization_callback: callable or msrest.serialization.Model + :param polling_method: The polling strategy to adopt + :type polling_method: ~azure.core.polling.AsyncPollingMethod + """ + + def __init__( + self, + client: Any, + initial_response: Any, + deserialization_callback: Callable[[Any], PollingReturnType_co], + polling_method: AsyncPollingMethod[PollingReturnType_co], + ): + self._polling_method = polling_method + self._done = False + + # This implicit test avoids bringing in an explicit dependency on Model directly + try: + deserialization_callback = deserialization_callback.deserialize # type: ignore + except AttributeError: + pass + + self._polling_method.initialize(client, initial_response, deserialization_callback) + + def polling_method(self) -> AsyncPollingMethod[PollingReturnType_co]: + """Return the polling method associated to this poller. + + :return: The polling method associated to this poller. + :rtype: ~azure.core.polling.AsyncPollingMethod + """ + return self._polling_method + + def continuation_token(self) -> str: + """Return a continuation token that allows to restart the poller later. + + :returns: An opaque continuation token + :rtype: str + """ + return self._polling_method.get_continuation_token() + + @classmethod + def from_continuation_token( + cls, polling_method: AsyncPollingMethod[PollingReturnType_co], continuation_token: str, **kwargs: Any + ) -> "AsyncLROPoller[PollingReturnType_co]": + ( + client, + initial_response, + deserialization_callback, + ) = polling_method.from_continuation_token(continuation_token, **kwargs) + return cls(client, initial_response, deserialization_callback, polling_method) + + def status(self) -> str: + """Returns the current status string. + + :returns: The current status string + :rtype: str + """ + return self._polling_method.status() + + async def result(self) -> PollingReturnType_co: + """Return the result of the long running operation. + + :returns: The deserialized resource of the long running operation, if one is available. + :rtype: any or None + :raises ~azure.core.exceptions.HttpResponseError: Server problem with the query. + """ + await self.wait() + return self._polling_method.resource() + + def __await__(self) -> Generator[Any, None, PollingReturnType_co]: + return self.result().__await__() + + async def wait(self) -> None: + """Wait on the long running operation. + + :raises ~azure.core.exceptions.HttpResponseError: Server problem with the query. + """ + try: + await self._polling_method.run() + except AzureError as error: + if not error.continuation_token: + try: + error.continuation_token = self.continuation_token() + except Exception as err: # pylint: disable=broad-except + _LOGGER.warning("Unable to retrieve continuation token: %s", err) + error.continuation_token = None + raise + self._done = True + + def done(self) -> bool: + """Check status of the long running operation. + + :returns: 'True' if the process has completed, else 'False'. + :rtype: bool + """ + return self._done diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/_poller.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/_poller.py new file mode 100644 index 0000000000000000000000000000000000000000..14e6ed2085e0b149250d73f442341b01233e089e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/_poller.py @@ -0,0 +1,303 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import base64 +import logging +import threading +import uuid +from typing import TypeVar, Generic, Any, Callable, Optional, Tuple, List +from azure.core.exceptions import AzureError +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.common import with_current_context + + +PollingReturnType_co = TypeVar("PollingReturnType_co", covariant=True) +DeserializationCallbackType = Any + +_LOGGER = logging.getLogger(__name__) + + +class PollingMethod(Generic[PollingReturnType_co]): + """ABC class for polling method.""" + + def initialize( + self, client: Any, initial_response: Any, deserialization_callback: DeserializationCallbackType + ) -> None: + raise NotImplementedError("This method needs to be implemented") + + def run(self) -> None: + raise NotImplementedError("This method needs to be implemented") + + def status(self) -> str: + raise NotImplementedError("This method needs to be implemented") + + def finished(self) -> bool: + raise NotImplementedError("This method needs to be implemented") + + def resource(self) -> PollingReturnType_co: + raise NotImplementedError("This method needs to be implemented") + + def get_continuation_token(self) -> str: + raise TypeError("Polling method '{}' doesn't support get_continuation_token".format(self.__class__.__name__)) + + @classmethod + def from_continuation_token( + cls, continuation_token: str, **kwargs: Any + ) -> Tuple[Any, Any, DeserializationCallbackType]: + raise TypeError("Polling method '{}' doesn't support from_continuation_token".format(cls.__name__)) + + +class _SansIONoPolling(Generic[PollingReturnType_co]): + _deserialization_callback: Callable[[Any], PollingReturnType_co] + """Deserialization callback passed during initialization""" + + def __init__(self): + self._initial_response = None + + def initialize( + self, + _: Any, + initial_response: Any, + deserialization_callback: Callable[[Any], PollingReturnType_co], + ) -> None: + self._initial_response = initial_response + self._deserialization_callback = deserialization_callback + + def status(self) -> str: + """Return the current status. + + :rtype: str + :return: The current status + """ + return "succeeded" + + def finished(self) -> bool: + """Is this polling finished? + + :rtype: bool + :return: Whether this polling is finished + """ + return True + + def resource(self) -> PollingReturnType_co: + return self._deserialization_callback(self._initial_response) + + def get_continuation_token(self) -> str: + import pickle + + return base64.b64encode(pickle.dumps(self._initial_response)).decode("ascii") + + @classmethod + def from_continuation_token( + cls, continuation_token: str, **kwargs: Any + ) -> Tuple[Any, Any, Callable[[Any], PollingReturnType_co]]: + try: + deserialization_callback = kwargs["deserialization_callback"] + except KeyError: + raise ValueError("Need kwarg 'deserialization_callback' to be recreated from continuation_token") from None + import pickle + + initial_response = pickle.loads(base64.b64decode(continuation_token)) # nosec + return None, initial_response, deserialization_callback + + +class NoPolling(_SansIONoPolling[PollingReturnType_co], PollingMethod[PollingReturnType_co]): + """An empty poller that returns the deserialized initial response.""" + + def run(self) -> None: + """Empty run, no polling.""" + + +class LROPoller(Generic[PollingReturnType_co]): + """Poller for long running operations. + + :param client: A pipeline service client + :type client: ~azure.core.PipelineClient + :param initial_response: The initial call response + :type initial_response: ~azure.core.pipeline.PipelineResponse + :param deserialization_callback: A callback that takes a Response and return a deserialized object. + If a subclass of Model is given, this passes "deserialize" as callback. + :type deserialization_callback: callable or msrest.serialization.Model + :param polling_method: The polling strategy to adopt + :type polling_method: ~azure.core.polling.PollingMethod + """ + + def __init__( + self, + client: Any, + initial_response: Any, + deserialization_callback: Callable[[Any], PollingReturnType_co], + polling_method: PollingMethod[PollingReturnType_co], + ) -> None: + self._callbacks: List[Callable] = [] + self._polling_method = polling_method + + # This implicit test avoids bringing in an explicit dependency on Model directly + try: + deserialization_callback = deserialization_callback.deserialize # type: ignore + except AttributeError: + pass + + # Might raise a CloudError + self._polling_method.initialize(client, initial_response, deserialization_callback) + + # Prepare thread execution + self._thread = None + self._done = threading.Event() + self._exception = None + if self._polling_method.finished(): + self._done.set() + else: + self._thread = threading.Thread( + target=with_current_context(self._start), + name="LROPoller({})".format(uuid.uuid4()), + ) + self._thread.daemon = True + self._thread.start() + + def _start(self): + """Start the long running operation. + On completion, runs any callbacks. + """ + try: + self._polling_method.run() + except AzureError as error: + if not error.continuation_token: + try: + error.continuation_token = self.continuation_token() + except Exception as err: # pylint: disable=broad-except + _LOGGER.warning("Unable to retrieve continuation token: %s", err) + error.continuation_token = None + + self._exception = error + except Exception as error: # pylint: disable=broad-except + self._exception = error + + finally: + self._done.set() + + callbacks, self._callbacks = self._callbacks, [] + while callbacks: + for call in callbacks: + call(self._polling_method) + callbacks, self._callbacks = self._callbacks, [] + + def polling_method(self) -> PollingMethod[PollingReturnType_co]: + """Return the polling method associated to this poller. + + :return: The polling method + :rtype: ~azure.core.polling.PollingMethod + """ + return self._polling_method + + def continuation_token(self) -> str: + """Return a continuation token that allows to restart the poller later. + + :returns: An opaque continuation token + :rtype: str + """ + return self._polling_method.get_continuation_token() + + @classmethod + def from_continuation_token( + cls, polling_method: PollingMethod[PollingReturnType_co], continuation_token: str, **kwargs: Any + ) -> "LROPoller[PollingReturnType_co]": + ( + client, + initial_response, + deserialization_callback, + ) = polling_method.from_continuation_token(continuation_token, **kwargs) + return cls(client, initial_response, deserialization_callback, polling_method) + + def status(self) -> str: + """Returns the current status string. + + :returns: The current status string + :rtype: str + """ + return self._polling_method.status() + + def result(self, timeout: Optional[float] = None) -> PollingReturnType_co: + """Return the result of the long running operation, or + the result available after the specified timeout. + + :param float timeout: Period of time to wait before getting back control. + :returns: The deserialized resource of the long running operation, if one is available. + :rtype: any or None + :raises ~azure.core.exceptions.HttpResponseError: Server problem with the query. + """ + self.wait(timeout) + return self._polling_method.resource() + + @distributed_trace + def wait(self, timeout: Optional[float] = None) -> None: + """Wait on the long running operation for a specified length + of time. You can check if this call as ended with timeout with the + "done()" method. + + :param float timeout: Period of time to wait for the long running + operation to complete (in seconds). + :raises ~azure.core.exceptions.HttpResponseError: Server problem with the query. + """ + if self._thread is None: + return + self._thread.join(timeout=timeout) + try: + # Let's handle possible None in forgiveness here + # https://github.com/python/mypy/issues/8165 + raise self._exception # type: ignore + except TypeError: # Was None + pass + + def done(self) -> bool: + """Check status of the long running operation. + + :returns: 'True' if the process has completed, else 'False'. + :rtype: bool + """ + return self._thread is None or not self._thread.is_alive() + + def add_done_callback(self, func: Callable) -> None: + """Add callback function to be run once the long running operation + has completed - regardless of the status of the operation. + + :param callable func: Callback function that takes at least one + argument, a completed LongRunningOperation. + """ + # Still use "_done" and not "done", since CBs are executed inside the thread. + if self._done.is_set(): + func(self._polling_method) + # Let's add them still, for consistency (if you wish to access to it for some reasons) + self._callbacks.append(func) + + def remove_done_callback(self, func: Callable) -> None: + """Remove a callback from the long running operation. + + :param callable func: The function to be removed from the callbacks. + :raises ValueError: if the long running operation has already completed. + """ + if self._done is None or self._done.is_set(): + raise ValueError("Process is complete.") + self._callbacks = [c for c in self._callbacks if c != func] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/async_base_polling.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/async_base_polling.py new file mode 100644 index 0000000000000000000000000000000000000000..8272d42ad443207299f58ac11a6b425281291d4e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/async_base_polling.py @@ -0,0 +1,180 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from typing import TypeVar, cast, Union +from ..exceptions import HttpResponseError +from .base_polling import ( + _failed, + BadStatus, + BadResponse, + OperationFailed, + _SansIOLROBasePolling, + _raise_if_bad_http_status_and_method, +) +from ._async_poller import AsyncPollingMethod +from ..pipeline._tools import is_rest +from .. import AsyncPipelineClient +from ..pipeline import PipelineResponse +from ..pipeline.transport import ( + HttpRequest as LegacyHttpRequest, + AsyncHttpTransport, + AsyncHttpResponse as LegacyAsyncHttpResponse, +) +from ..rest import HttpRequest, AsyncHttpResponse + +HttpRequestType = Union[LegacyHttpRequest, HttpRequest] +AsyncHttpResponseType = Union[LegacyAsyncHttpResponse, AsyncHttpResponse] +HttpRequestTypeVar = TypeVar("HttpRequestTypeVar", bound=HttpRequestType) +AsyncHttpResponseTypeVar = TypeVar("AsyncHttpResponseTypeVar", bound=AsyncHttpResponseType) + + +PollingReturnType_co = TypeVar("PollingReturnType_co", covariant=True) + +__all__ = ["AsyncLROBasePolling"] + + +class AsyncLROBasePolling( + _SansIOLROBasePolling[ + PollingReturnType_co, + AsyncPipelineClient[HttpRequestTypeVar, AsyncHttpResponseTypeVar], + HttpRequestTypeVar, + AsyncHttpResponseTypeVar, + ], + AsyncPollingMethod[PollingReturnType_co], +): + """A base LRO async poller. + + This assumes a basic flow: + - I analyze the response to decide the polling approach + - I poll + - I ask the final resource depending of the polling approach + + If your polling need are more specific, you could implement a PollingMethod directly + """ + + _initial_response: PipelineResponse[HttpRequestTypeVar, AsyncHttpResponseTypeVar] + """Store the initial response.""" + + _pipeline_response: PipelineResponse[HttpRequestTypeVar, AsyncHttpResponseTypeVar] + """Store the latest received HTTP response, initialized by the first answer.""" + + @property + def _transport(self) -> AsyncHttpTransport[HttpRequestTypeVar, AsyncHttpResponseTypeVar]: + return self._client._pipeline._transport # pylint: disable=protected-access + + async def run(self) -> None: + try: + await self._poll() + + except BadStatus as err: + self._status = "Failed" + raise HttpResponseError(response=self._pipeline_response.http_response, error=err) from err + + except BadResponse as err: + self._status = "Failed" + raise HttpResponseError( + response=self._pipeline_response.http_response, + message=str(err), + error=err, + ) from err + + except OperationFailed as err: + raise HttpResponseError(response=self._pipeline_response.http_response, error=err) from err + + async def _poll(self) -> None: + """Poll status of operation so long as operation is incomplete and + we have an endpoint to query. + + :raises: OperationFailed if operation status 'Failed' or 'Canceled'. + :raises: BadStatus if response status invalid. + :raises: BadResponse if response invalid. + """ + if not self.finished(): + await self.update_status() + while not self.finished(): + await self._delay() + await self.update_status() + + if _failed(self.status()): + raise OperationFailed("Operation failed or canceled") + + final_get_url = self._operation.get_final_get_url(self._pipeline_response) + if final_get_url: + self._pipeline_response = await self.request_status(final_get_url) + _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) + + async def _sleep(self, delay: float) -> None: + await self._transport.sleep(delay) + + async def _delay(self) -> None: + """Check for a 'retry-after' header to set timeout, + otherwise use configured timeout. + """ + delay = self._extract_delay() + await self._sleep(delay) + + async def update_status(self) -> None: + """Update the current status of the LRO.""" + self._pipeline_response = await self.request_status(self._operation.get_polling_url()) + _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) + self._status = self._operation.get_status(self._pipeline_response) + + async def request_status(self, status_link: str) -> PipelineResponse[HttpRequestTypeVar, AsyncHttpResponseTypeVar]: + """Do a simple GET to this status link. + + This method re-inject 'x-ms-client-request-id'. + + :param str status_link: URL to poll. + :rtype: azure.core.pipeline.PipelineResponse + :return: The response of the status request. + """ + if self._path_format_arguments: + status_link = self._client.format_url(status_link, **self._path_format_arguments) + # Re-inject 'x-ms-client-request-id' while polling + if "request_id" not in self._operation_config: + self._operation_config["request_id"] = self._get_request_id() + + if is_rest(self._initial_response.http_response): + rest_request = cast(HttpRequestTypeVar, HttpRequest("GET", status_link)) + # Need a cast, as "_return_pipeline_response" mutate the return type, and that return type is not + # declared in the typing of "send_request" + return cast( + PipelineResponse[HttpRequestTypeVar, AsyncHttpResponseTypeVar], + await self._client.send_request(rest_request, _return_pipeline_response=True, **self._operation_config), + ) + + # Legacy HttpRequest and AsyncHttpResponse from azure.core.pipeline.transport + # casting things here, as we don't want the typing system to know + # about the legacy APIs. + request = cast(HttpRequestTypeVar, self._client.get(status_link)) + return cast( + PipelineResponse[HttpRequestTypeVar, AsyncHttpResponseTypeVar], + await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **self._operation_config + ), + ) + + +__all__ = ["AsyncLROBasePolling"] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/base_polling.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/base_polling.py new file mode 100644 index 0000000000000000000000000000000000000000..854a53758de3db0bdd695e02af5c7a9614ecd3e4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/polling/base_polling.py @@ -0,0 +1,857 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import abc +import base64 +import json +from enum import Enum +from typing import ( + Optional, + Any, + Tuple, + Callable, + Dict, + Sequence, + Generic, + TypeVar, + cast, + Union, +) + +from ..exceptions import HttpResponseError, DecodeError +from . import PollingMethod +from ..pipeline.policies._utils import get_retry_after +from ..pipeline._tools import is_rest +from .._enum_meta import CaseInsensitiveEnumMeta +from .. import PipelineClient +from ..pipeline import PipelineResponse +from ..pipeline.transport import ( + HttpTransport, + HttpRequest as LegacyHttpRequest, + HttpResponse as LegacyHttpResponse, + AsyncHttpResponse as LegacyAsyncHttpResponse, +) +from ..rest import HttpRequest, HttpResponse, AsyncHttpResponse + + +HttpRequestType = Union[LegacyHttpRequest, HttpRequest] +HttpResponseType = Union[LegacyHttpResponse, HttpResponse] # Sync only +AllHttpResponseType = Union[ + LegacyHttpResponse, HttpResponse, LegacyAsyncHttpResponse, AsyncHttpResponse +] # Sync or async +LegacyPipelineResponseType = PipelineResponse[LegacyHttpRequest, LegacyHttpResponse] +NewPipelineResponseType = PipelineResponse[HttpRequest, HttpResponse] +PipelineResponseType = PipelineResponse[HttpRequestType, HttpResponseType] +HttpRequestTypeVar = TypeVar("HttpRequestTypeVar", bound=HttpRequestType) +HttpResponseTypeVar = TypeVar("HttpResponseTypeVar", bound=HttpResponseType) # Sync only +AllHttpResponseTypeVar = TypeVar("AllHttpResponseTypeVar", bound=AllHttpResponseType) # Sync or async + +ABC = abc.ABC +PollingReturnType_co = TypeVar("PollingReturnType_co", covariant=True) +PipelineClientType = TypeVar("PipelineClientType") +HTTPResponseType_co = TypeVar("HTTPResponseType_co", covariant=True) +HTTPRequestType_co = TypeVar("HTTPRequestType_co", covariant=True) + + +_FINISHED = frozenset(["succeeded", "canceled", "failed"]) +_FAILED = frozenset(["canceled", "failed"]) +_SUCCEEDED = frozenset(["succeeded"]) + + +def _get_content(response: AllHttpResponseType) -> bytes: + """Get the content of this response. This is designed specifically to avoid + a warning of mypy for body() access, as this method is deprecated. + + :param response: The response object. + :type response: any + :return: The content of this response. + :rtype: bytes + """ + if isinstance(response, (LegacyHttpResponse, LegacyAsyncHttpResponse)): + return response.body() + return response.content + + +def _finished(status): + if hasattr(status, "value"): + status = status.value + return str(status).lower() in _FINISHED + + +def _failed(status): + if hasattr(status, "value"): + status = status.value + return str(status).lower() in _FAILED + + +def _succeeded(status): + if hasattr(status, "value"): + status = status.value + return str(status).lower() in _SUCCEEDED + + +class BadStatus(Exception): + pass + + +class BadResponse(Exception): + pass + + +class OperationFailed(Exception): + pass + + +def _as_json(response: AllHttpResponseType) -> Dict[str, Any]: + """Assuming this is not empty, return the content as JSON. + + Result/exceptions is not determined if you call this method without testing _is_empty. + + :param response: The response object. + :type response: any + :return: The content of this response as dict. + :rtype: dict + :raises: DecodeError if response body contains invalid json data. + """ + try: + return json.loads(response.text()) + except ValueError as err: + raise DecodeError("Error occurred in deserializing the response body.") from err + + +def _raise_if_bad_http_status_and_method(response: AllHttpResponseType) -> None: + """Check response status code is valid. + + Must be 200, 201, 202, or 204. + + :param response: The response object. + :type response: any + :raises: BadStatus if invalid status. + """ + code = response.status_code + if code in {200, 201, 202, 204}: + return + raise BadStatus("Invalid return status {!r} for {!r} operation".format(code, response.request.method)) + + +def _is_empty(response: AllHttpResponseType) -> bool: + """Check if response body contains meaningful content. + + :param response: The response object. + :type response: any + :return: True if response body is empty, False otherwise. + :rtype: bool + """ + return not bool(_get_content(response)) + + +class LongRunningOperation(ABC, Generic[HTTPRequestType_co, HTTPResponseType_co]): + """Protocol to implement for a long running operation algorithm.""" + + @abc.abstractmethod + def can_poll( + self, + pipeline_response: PipelineResponse[HTTPRequestType_co, HTTPResponseType_co], + ) -> bool: + """Answer if this polling method could be used. + + :param pipeline_response: Initial REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: True if this polling method could be used, False otherwise. + :rtype: bool + """ + raise NotImplementedError() + + @abc.abstractmethod + def get_polling_url(self) -> str: + """Return the polling URL. + + :return: The polling URL. + :rtype: str + """ + raise NotImplementedError() + + @abc.abstractmethod + def set_initial_status( + self, + pipeline_response: PipelineResponse[HTTPRequestType_co, HTTPResponseType_co], + ) -> str: + """Process first response after initiating long running operation. + + :param pipeline_response: Initial REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: The initial status. + :rtype: str + """ + raise NotImplementedError() + + @abc.abstractmethod + def get_status( + self, + pipeline_response: PipelineResponse[HTTPRequestType_co, HTTPResponseType_co], + ) -> str: + """Return the status string extracted from this response. + + :param pipeline_response: The response object. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: The status string. + :rtype: str + """ + raise NotImplementedError() + + @abc.abstractmethod + def get_final_get_url( + self, + pipeline_response: PipelineResponse[HTTPRequestType_co, HTTPResponseType_co], + ) -> Optional[str]: + """If a final GET is needed, returns the URL. + + :param pipeline_response: Success REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: The URL to the final GET, or None if no final GET is needed. + :rtype: str or None + """ + raise NotImplementedError() + + +class _LroOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Known LRO options from Swagger.""" + + FINAL_STATE_VIA = "final-state-via" + + +class _FinalStateViaOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Possible final-state-via options.""" + + AZURE_ASYNC_OPERATION_FINAL_STATE = "azure-async-operation" + LOCATION_FINAL_STATE = "location" + OPERATION_LOCATION_FINAL_STATE = "operation-location" + + +class OperationResourcePolling(LongRunningOperation[HttpRequestTypeVar, AllHttpResponseTypeVar]): + """Implements a operation resource polling, typically from Operation-Location. + + :param str operation_location_header: Name of the header to return operation format (default 'operation-location') + :keyword dict[str, any] lro_options: Additional options for LRO. For more information, see + https://aka.ms/azsdk/autorest/openapi/lro-options + """ + + _async_url: str + """Url to resource monitor (AzureAsyncOperation or Operation-Location)""" + + _location_url: Optional[str] + """Location header if present""" + + _request: Any + """The initial request done""" + + def __init__( + self, operation_location_header: str = "operation-location", *, lro_options: Optional[Dict[str, Any]] = None + ): + self._operation_location_header = operation_location_header + self._location_url = None + self._lro_options = lro_options or {} + + def can_poll(self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar]) -> bool: + """Check if status monitor header (e.g. Operation-Location) is present. + + :param pipeline_response: Initial REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: True if this polling method could be used, False otherwise. + :rtype: bool + """ + response = pipeline_response.http_response + return self._operation_location_header in response.headers + + def get_polling_url(self) -> str: + """Return the polling URL. + + Will extract it from the defined header to read (e.g. Operation-Location) + + :return: The polling URL. + :rtype: str + """ + return self._async_url + + def get_final_get_url( + self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar] + ) -> Optional[str]: + """If a final GET is needed, returns the URL. + + :param pipeline_response: Success REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: The URL to the final GET, or None if no final GET is needed. + :rtype: str or None + """ + if ( + self._lro_options.get(_LroOption.FINAL_STATE_VIA) == _FinalStateViaOption.LOCATION_FINAL_STATE + and self._location_url + ): + return self._location_url + if ( + self._lro_options.get(_LroOption.FINAL_STATE_VIA) + in [ + _FinalStateViaOption.AZURE_ASYNC_OPERATION_FINAL_STATE, + _FinalStateViaOption.OPERATION_LOCATION_FINAL_STATE, + ] + and self._request.method == "POST" + ): + return None + response = pipeline_response.http_response + if not _is_empty(response): + body = _as_json(response) + # https://github.com/microsoft/api-guidelines/blob/vNext/Guidelines.md#target-resource-location + resource_location = body.get("resourceLocation") + if resource_location: + return resource_location + + if self._request.method in {"PUT", "PATCH"}: + return self._request.url + + if self._request.method == "POST" and self._location_url: + return self._location_url + + return None + + def set_initial_status( + self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar] + ) -> str: + """Process first response after initiating long running operation. + + :param pipeline_response: Initial REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: The initial status. + :rtype: str + """ + self._request = pipeline_response.http_response.request + response = pipeline_response.http_response + + self._set_async_url_if_present(response) + + if response.status_code in {200, 201, 202, 204} and self._async_url: + # Check if we can extract status from initial response, if present + try: + return self.get_status(pipeline_response) + # Wide catch, it may not even be JSON at all, deserialization is lenient + except Exception: # pylint: disable=broad-except + pass + return "InProgress" + raise OperationFailed("Operation failed or canceled") + + def _set_async_url_if_present(self, response: AllHttpResponseTypeVar) -> None: + self._async_url = response.headers[self._operation_location_header] + + location_url = response.headers.get("location") + if location_url: + self._location_url = location_url + + def get_status(self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar]) -> str: + """Process the latest status update retrieved from an "Operation-Location" header. + + :param pipeline_response: Initial REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: The status string. + :rtype: str + :raises: BadResponse if response has no body, or body does not contain status. + """ + response = pipeline_response.http_response + if _is_empty(response): + raise BadResponse("The response from long running operation does not contain a body.") + + body = _as_json(response) + status = body.get("status") + if not status: + raise BadResponse("No status found in body") + return status + + +class LocationPolling(LongRunningOperation[HttpRequestTypeVar, AllHttpResponseTypeVar]): + """Implements a Location polling.""" + + _location_url: str + """Location header""" + + def can_poll(self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar]) -> bool: + """True if contains a Location header + + :param pipeline_response: Initial REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: True if this polling method could be used, False otherwise. + :rtype: bool + """ + response = pipeline_response.http_response + return "location" in response.headers + + def get_polling_url(self) -> str: + """Return the Location header value. + + :return: The polling URL. + :rtype: str + """ + return self._location_url + + def get_final_get_url( + self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar] + ) -> Optional[str]: + """If a final GET is needed, returns the URL. + + Always return None for a Location polling. + + :param pipeline_response: Success REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: Always None for this implementation. + :rtype: None + """ + return None + + def set_initial_status( + self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar] + ) -> str: + """Process first response after initiating long running operation. + + :param pipeline_response: Initial REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: The initial status. + :rtype: str + """ + response = pipeline_response.http_response + + self._location_url = response.headers["location"] + + if response.status_code in {200, 201, 202, 204} and self._location_url: + return "InProgress" + raise OperationFailed("Operation failed or canceled") + + def get_status(self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar]) -> str: + """Return the status string extracted from this response. + + For Location polling, it means the status monitor returns 202. + + :param pipeline_response: Initial REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: The status string. + :rtype: str + """ + response = pipeline_response.http_response + if "location" in response.headers: + self._location_url = response.headers["location"] + + return "InProgress" if response.status_code == 202 else "Succeeded" + + +class StatusCheckPolling(LongRunningOperation[HttpRequestTypeVar, AllHttpResponseTypeVar]): + """Should be the fallback polling, that don't poll but exit successfully + if not other polling are detected and status code is 2xx. + """ + + def can_poll(self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar]) -> bool: + """Answer if this polling method could be used. + + For this implementation, always True. + + :param pipeline_response: Initial REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: True if this polling method could be used, False otherwise. + :rtype: bool + """ + return True + + def get_polling_url(self) -> str: + """Return the polling URL. + + This is not implemented for this polling, since we're never supposed to loop. + + :return: The polling URL. + :rtype: str + """ + raise ValueError("This polling doesn't support polling url") + + def set_initial_status( + self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar] + ) -> str: + """Process first response after initiating long running operation. + + Will succeed immediately. + + :param pipeline_response: Initial REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: The initial status. + :rtype: str + """ + return "Succeeded" + + def get_status(self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar]) -> str: + """Return the status string extracted from this response. + + Only possible status is success. + + :param pipeline_response: Initial REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: The status string. + :rtype: str + """ + return "Succeeded" + + def get_final_get_url( + self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar] + ) -> Optional[str]: + """If a final GET is needed, returns the URL. + + :param pipeline_response: Success REST call response. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :rtype: str + :return: Always None for this implementation. + """ + return None + + +class _SansIOLROBasePolling( + Generic[PollingReturnType_co, PipelineClientType, HttpRequestTypeVar, AllHttpResponseTypeVar] +): # pylint: disable=too-many-instance-attributes + """A base class that has no opinion on IO, to help mypy be accurate. + + :param float timeout: Default polling internal in absence of Retry-After header, in seconds. + :param list[LongRunningOperation] lro_algorithms: Ordered list of LRO algorithms to use. + :param lro_options: Additional options for LRO. For more information, see the algorithm's docstring. + :type lro_options: dict[str, any] + :param path_format_arguments: A dictionary of the format arguments to be used to format the URL. + :type path_format_arguments: dict[str, str] + """ + + _deserialization_callback: Callable[[Any], PollingReturnType_co] + """The deserialization callback that returns the final instance.""" + + _operation: LongRunningOperation[HttpRequestTypeVar, AllHttpResponseTypeVar] + """The algorithm this poller has decided to use. Will loop through 'can_poll' of the input algorithms to decide.""" + + _status: str + """Hold the current status of this poller""" + + _client: PipelineClientType + """The Azure Core Pipeline client used to make request.""" + + def __init__( + self, + timeout: float = 30, + lro_algorithms: Optional[Sequence[LongRunningOperation[HttpRequestTypeVar, AllHttpResponseTypeVar]]] = None, + lro_options: Optional[Dict[str, Any]] = None, + path_format_arguments: Optional[Dict[str, str]] = None, + **operation_config: Any + ): + self._lro_algorithms = lro_algorithms or [ + OperationResourcePolling(lro_options=lro_options), + LocationPolling(), + StatusCheckPolling(), + ] + + self._timeout = timeout + self._operation_config = operation_config + self._lro_options = lro_options + self._path_format_arguments = path_format_arguments + + def initialize( + self, + client: PipelineClientType, + initial_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar], + deserialization_callback: Callable[ + [PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar]], PollingReturnType_co + ], + ) -> None: + """Set the initial status of this LRO. + + :param client: The Azure Core Pipeline client used to make request. + :type client: ~azure.core.pipeline.PipelineClient + :param initial_response: The initial response for the call. + :type initial_response: ~azure.core.pipeline.PipelineResponse + :param deserialization_callback: A callback function to deserialize the final response. + :type deserialization_callback: callable + :raises: HttpResponseError if initial status is incorrect LRO state + """ + self._client = client + self._pipeline_response = ( # pylint: disable=attribute-defined-outside-init + self._initial_response # pylint: disable=attribute-defined-outside-init + ) = initial_response + self._deserialization_callback = deserialization_callback + + for operation in self._lro_algorithms: + if operation.can_poll(initial_response): + self._operation = operation + break + else: + raise BadResponse("Unable to find status link for polling.") + + try: + _raise_if_bad_http_status_and_method(self._initial_response.http_response) + self._status = self._operation.set_initial_status(initial_response) + + except BadStatus as err: + self._status = "Failed" + raise HttpResponseError(response=initial_response.http_response, error=err) from err + except BadResponse as err: + self._status = "Failed" + raise HttpResponseError(response=initial_response.http_response, message=str(err), error=err) from err + except OperationFailed as err: + raise HttpResponseError(response=initial_response.http_response, error=err) from err + + def get_continuation_token(self) -> str: + import pickle + + return base64.b64encode(pickle.dumps(self._initial_response)).decode("ascii") + + @classmethod + def from_continuation_token( + cls, continuation_token: str, **kwargs: Any + ) -> Tuple[Any, Any, Callable[[Any], PollingReturnType_co]]: + try: + client = kwargs["client"] + except KeyError: + raise ValueError("Need kwarg 'client' to be recreated from continuation_token") from None + + try: + deserialization_callback = kwargs["deserialization_callback"] + except KeyError: + raise ValueError("Need kwarg 'deserialization_callback' to be recreated from continuation_token") from None + + import pickle + + initial_response = pickle.loads(base64.b64decode(continuation_token)) # nosec + # Restore the transport in the context + initial_response.context.transport = client._pipeline._transport # pylint: disable=protected-access + return client, initial_response, deserialization_callback + + def status(self) -> str: + """Return the current status as a string. + + :rtype: str + :return: The current status. + """ + if not self._operation: + raise ValueError("set_initial_status was never called. Did you give this instance to a poller?") + return self._status + + def finished(self) -> bool: + """Is this polling finished? + + :rtype: bool + :return: True if finished, False otherwise. + """ + return _finished(self.status()) + + def resource(self) -> PollingReturnType_co: + """Return the built resource. + + :rtype: any + :return: The built resource. + """ + return self._parse_resource(self._pipeline_response) + + def _parse_resource( + self, pipeline_response: PipelineResponse[HttpRequestTypeVar, AllHttpResponseTypeVar] + ) -> PollingReturnType_co: + """Assuming this response is a resource, use the deserialization callback to parse it. + If body is empty, assuming no resource to return. + + :param pipeline_response: The response object. + :type pipeline_response: ~azure.core.pipeline.PipelineResponse + :return: The parsed resource. + :rtype: any + """ + response = pipeline_response.http_response + if not _is_empty(response): + return self._deserialization_callback(pipeline_response) + + # This "type ignore" has been discussed with architects. + # We have a typing problem that if the Swagger/TSP describes a return type (PollingReturnType_co is not None), + # BUT the returned payload is actually empty, we don't want to fail, but return None. + # To be clean, we would have to make the polling return type Optional "just in case the Swagger/TSP is wrong". + # This is reducing the quality and the value of the typing annotations + # for a case that is not supposed to happen in the first place. So we decided to ignore the type error here. + return None # type: ignore + + def _get_request_id(self) -> str: + return self._pipeline_response.http_response.request.headers["x-ms-client-request-id"] + + def _extract_delay(self) -> float: + delay = get_retry_after(self._pipeline_response) + if delay: + return delay + return self._timeout + + +class LROBasePolling( + _SansIOLROBasePolling[ + PollingReturnType_co, + PipelineClient[HttpRequestTypeVar, HttpResponseTypeVar], + HttpRequestTypeVar, + HttpResponseTypeVar, + ], + PollingMethod[PollingReturnType_co], +): # pylint: disable=too-many-instance-attributes + """A base LRO poller. + + This assumes a basic flow: + - I analyze the response to decide the polling approach + - I poll + - I ask the final resource depending of the polling approach + + If your polling need are more specific, you could implement a PollingMethod directly + """ + + _initial_response: PipelineResponse[HttpRequestTypeVar, HttpResponseTypeVar] + """Store the initial response.""" + + _pipeline_response: PipelineResponse[HttpRequestTypeVar, HttpResponseTypeVar] + """Store the latest received HTTP response, initialized by the first answer.""" + + @property + def _transport(self) -> HttpTransport[HttpRequestTypeVar, HttpResponseTypeVar]: + return self._client._pipeline._transport # pylint: disable=protected-access + + def __getattribute__(self, name: str) -> Any: + """Find the right method for the job. + + This contains a workaround for azure-mgmt-core 1.0.0 to 1.4.0, where the MRO + is changing when azure-core was refactored in 1.27.0. The MRO change was causing + AsyncARMPolling to look-up the wrong methods and find the non-async ones. + + :param str name: The name of the attribute to retrieve. + :rtype: Any + :return: The attribute value. + """ + cls = object.__getattribute__(self, "__class__") + if cls.__name__ == "AsyncARMPolling" and name in [ + "run", + "update_status", + "request_status", + "_sleep", + "_delay", + "_poll", + ]: + return getattr(super(LROBasePolling, self), name) + return super().__getattribute__(name) + + def run(self) -> None: + try: + self._poll() + + except BadStatus as err: + self._status = "Failed" + raise HttpResponseError(response=self._pipeline_response.http_response, error=err) from err + + except BadResponse as err: + self._status = "Failed" + raise HttpResponseError( + response=self._pipeline_response.http_response, + message=str(err), + error=err, + ) from err + + except OperationFailed as err: + raise HttpResponseError(response=self._pipeline_response.http_response, error=err) from err + + def _poll(self) -> None: + """Poll status of operation so long as operation is incomplete and + we have an endpoint to query. + + :raises: OperationFailed if operation status 'Failed' or 'Canceled'. + :raises: BadStatus if response status invalid. + :raises: BadResponse if response invalid. + """ + if not self.finished(): + self.update_status() + while not self.finished(): + self._delay() + self.update_status() + + if _failed(self.status()): + raise OperationFailed("Operation failed or canceled") + + final_get_url = self._operation.get_final_get_url(self._pipeline_response) + if final_get_url: + self._pipeline_response = self.request_status(final_get_url) + _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) + + def _sleep(self, delay: float) -> None: + self._transport.sleep(delay) + + def _delay(self) -> None: + """Check for a 'retry-after' header to set timeout, + otherwise use configured timeout. + """ + delay = self._extract_delay() + self._sleep(delay) + + def update_status(self) -> None: + """Update the current status of the LRO.""" + self._pipeline_response = self.request_status(self._operation.get_polling_url()) + _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) + self._status = self._operation.get_status(self._pipeline_response) + + def request_status(self, status_link: str) -> PipelineResponse[HttpRequestTypeVar, HttpResponseTypeVar]: + """Do a simple GET to this status link. + + This method re-inject 'x-ms-client-request-id'. + + :param str status_link: The URL to poll. + :rtype: azure.core.pipeline.PipelineResponse + :return: The response of the status request. + """ + if self._path_format_arguments: + status_link = self._client.format_url(status_link, **self._path_format_arguments) + # Re-inject 'x-ms-client-request-id' while polling + if "request_id" not in self._operation_config: + self._operation_config["request_id"] = self._get_request_id() + + if is_rest(self._initial_response.http_response): + rest_request = cast(HttpRequestTypeVar, HttpRequest("GET", status_link)) + # Need a cast, as "_return_pipeline_response" mutate the return type, and that return type is not + # declared in the typing of "send_request" + return cast( + PipelineResponse[HttpRequestTypeVar, HttpResponseTypeVar], + self._client.send_request(rest_request, _return_pipeline_response=True, **self._operation_config), + ) + + # Legacy HttpRequest and HttpResponse from azure.core.pipeline.transport + # casting things here, as we don't want the typing system to know + # about the legacy APIs. + request = cast(HttpRequestTypeVar, self._client.get(status_link)) + return cast( + PipelineResponse[HttpRequestTypeVar, HttpResponseTypeVar], + self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **self._operation_config + ), + ) + + +__all__ = [ + "BadResponse", + "BadStatus", + "OperationFailed", + "LongRunningOperation", + "OperationResourcePolling", + "LocationPolling", + "StatusCheckPolling", + "LROBasePolling", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..078efaaa91c0d0f89fdfdf0603bb4f01fedc7eb7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/__init__.py @@ -0,0 +1,36 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from ._rest_py3 import ( + HttpRequest, + HttpResponse, + AsyncHttpResponse, +) + +__all__ = [ + "HttpRequest", + "HttpResponse", + "AsyncHttpResponse", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_aiohttp.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_aiohttp.py new file mode 100644 index 0000000000000000000000000000000000000000..64833e311c8624b2b1a4f9228647db21d11f233b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_aiohttp.py @@ -0,0 +1,228 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import collections.abc +import asyncio +from itertools import groupby +from typing import Iterator, cast +from multidict import CIMultiDict +from ._http_response_impl_async import ( + AsyncHttpResponseImpl, + AsyncHttpResponseBackcompatMixin, +) +from ..pipeline.transport._aiohttp import AioHttpStreamDownloadGenerator +from ..utils._pipeline_transport_rest_shared import _pad_attr_name, _aiohttp_body_helper +from ..exceptions import ResponseNotReadError + + +class _ItemsView(collections.abc.ItemsView): + def __init__(self, ref): + super().__init__(ref) + self._ref = ref + + def __iter__(self): + for key, groups in groupby(self._ref.__iter__(), lambda x: x[0]): + yield tuple([key, ", ".join(group[1] for group in groups)]) + + def __contains__(self, item): + if not (isinstance(item, (list, tuple)) and len(item) == 2): + return False + for k, v in self.__iter__(): + if item[0].lower() == k.lower() and item[1] == v: + return True + return False + + def __repr__(self): + return f"dict_items({list(self.__iter__())})" + + +class _KeysView(collections.abc.KeysView): + def __init__(self, items): + super().__init__(items) + self._items = items + + def __iter__(self) -> Iterator[str]: + for key, _ in self._items: + yield key + + def __contains__(self, key): + try: + for k in self.__iter__(): + if cast(str, key).lower() == k.lower(): + return True + except AttributeError: # Catch "lower()" if key not a string + pass + return False + + def __repr__(self) -> str: + return f"dict_keys({list(self.__iter__())})" + + +class _ValuesView(collections.abc.ValuesView): + def __init__(self, items): + super().__init__(items) + self._items = items + + def __iter__(self): + for _, value in self._items: + yield value + + def __contains__(self, value): + for v in self.__iter__(): + if value == v: + return True + return False + + def __repr__(self): + return f"dict_values({list(self.__iter__())})" + + +class _CIMultiDict(CIMultiDict): + """Dictionary with the support for duplicate case-insensitive keys.""" + + def __iter__(self): + return iter(self.keys()) + + def keys(self): + """Return a new view of the dictionary's keys. + + :return: A new view of the dictionary's keys + :rtype: ~collections.abc.KeysView + """ + return _KeysView(self.items()) + + def items(self): + """Return a new view of the dictionary's items. + + :return: A new view of the dictionary's items + :rtype: ~collections.abc.ItemsView + """ + return _ItemsView(super().items()) + + def values(self): + """Return a new view of the dictionary's values. + + :return: A new view of the dictionary's values + :rtype: ~collections.abc.ValuesView + """ + return _ValuesView(self.items()) + + def __getitem__(self, key: str) -> str: + return ", ".join(self.getall(key, [])) + + def get(self, key, default=None): + values = self.getall(key, None) + if values: + values = ", ".join(values) + return values or default + + +class _RestAioHttpTransportResponseBackcompatMixin(AsyncHttpResponseBackcompatMixin): + """Backcompat mixin for aiohttp responses. + + Need to add it's own mixin because it has function load_body, which other + transport responses don't have, and also because we need to synchronously + decompress the body if users call .body() + """ + + def body(self) -> bytes: + """Return the whole body as bytes in memory. + + Have to modify the default behavior here. In AioHttp, we do decompression + when accessing the body method. The behavior here is the same as if the + caller did an async read of the response first. But for backcompat reasons, + we need to support this decompression within the synchronous body method. + + :return: The response's bytes + :rtype: bytes + """ + return _aiohttp_body_helper(self) + + async def _load_body(self) -> None: + """Load in memory the body, so it could be accessible from sync methods.""" + self._content = await self.read() # type: ignore + + def __getattr__(self, attr): + backcompat_attrs = ["load_body"] + attr = _pad_attr_name(attr, backcompat_attrs) + return super().__getattr__(attr) + + +class RestAioHttpTransportResponse(AsyncHttpResponseImpl, _RestAioHttpTransportResponseBackcompatMixin): + def __init__(self, *, internal_response, decompress: bool = True, **kwargs): + headers = _CIMultiDict(internal_response.headers) + super().__init__( + internal_response=internal_response, + status_code=internal_response.status, + headers=headers, + content_type=headers.get("content-type"), + reason=internal_response.reason, + stream_download_generator=AioHttpStreamDownloadGenerator, + content=None, + **kwargs, + ) + self._decompress = decompress + self._decompressed_content = False + + def __getstate__(self): + state = self.__dict__.copy() + # Remove the unpicklable entries. + state["_internal_response"] = None # aiohttp response are not pickable (see headers comments) + state["headers"] = CIMultiDict(self.headers) # MultiDictProxy is not pickable + return state + + @property + def content(self) -> bytes: + """Return the response's content in bytes. + + :return: The response's content in bytes + :rtype: bytes + """ + if self._content is None: + raise ResponseNotReadError(self) + return _aiohttp_body_helper(self) + + async def read(self) -> bytes: + """Read the response's bytes into memory. + + :return: The response's bytes + :rtype: bytes + """ + if not self._content: + self._stream_download_check() + self._content = await self._internal_response.read() + await self._set_read_checks() + return _aiohttp_body_helper(self) + + async def close(self) -> None: + """Close the response. + + :return: None + :rtype: None + """ + if not self.is_closed: + self._is_closed = True + self._internal_response.close() + await asyncio.sleep(0) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_helpers.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..e7385fb069155f4fb359a8de820780d464f7d09a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_helpers.py @@ -0,0 +1,421 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from __future__ import annotations +import copy +import codecs +import email.message +from json import dumps +from typing import ( + Optional, + Union, + Mapping, + Sequence, + Tuple, + IO, + Any, + Iterable, + MutableMapping, + AsyncIterable, + cast, + Dict, + TYPE_CHECKING, +) +import xml.etree.ElementTree as ET +from urllib.parse import urlparse +from azure.core.serialization import AzureJSONEncoder +from ..utils._pipeline_transport_rest_shared import ( + _format_parameters_helper, + _pad_attr_name, + _prepare_multipart_body_helper, + _serialize_request, + _format_data_helper, + get_file_items, +) + +if TYPE_CHECKING: + # This avoid a circular import + from ._rest_py3 import HttpRequest + +################################### TYPES SECTION ######################### + +binary_type = str +PrimitiveData = Optional[Union[str, int, float, bool]] + +ParamsType = Mapping[str, Union[PrimitiveData, Sequence[PrimitiveData]]] + +FileContent = Union[str, bytes, IO[str], IO[bytes]] + +FileType = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], FileContent, Optional[str]], +] + +FilesType = Union[Mapping[str, FileType], Sequence[Tuple[str, FileType]]] + +ContentTypeBase = Union[str, bytes, Iterable[bytes]] +ContentType = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] + +DataType = Optional[Union[bytes, Dict[str, Union[str, int]]]] + +########################### HELPER SECTION ################################# + + +def _verify_data_object(name, value): + if not isinstance(name, str): + raise TypeError("Invalid type for data name. Expected str, got {}: {}".format(type(name), name)) + if value is not None and not isinstance(value, (str, bytes, int, float)): + raise TypeError("Invalid type for data value. Expected primitive type, got {}: {}".format(type(name), name)) + + +def set_urlencoded_body(data, has_files): + body = {} + default_headers = {} + for f, d in data.items(): + if not d: + continue + if isinstance(d, list): + for item in d: + _verify_data_object(f, item) + else: + _verify_data_object(f, d) + body[f] = d + if not has_files: + # little hacky, but for files we don't send a content type with + # boundary so requests / aiohttp etc deal with it + default_headers["Content-Type"] = "application/x-www-form-urlencoded" + return default_headers, body + + +def set_multipart_body(files: FilesType): + formatted_files = [(f, _format_data_helper(d)) for f, d in get_file_items(files) if d is not None] + return {}, dict(formatted_files) if isinstance(files, Mapping) else formatted_files + + +def set_xml_body(content): + headers = {} + bytes_content = ET.tostring(content, encoding="utf8") + body = bytes_content.replace(b"encoding='utf8'", b"encoding='utf-8'") + if body: + headers["Content-Length"] = str(len(body)) + return headers, body + + +def set_content_body( + content: Any, +) -> Tuple[MutableMapping[str, str], Optional[ContentTypeBase]]: + headers: MutableMapping[str, str] = {} + + if isinstance(content, ET.Element): + # XML body + return set_xml_body(content) + if isinstance(content, (str, bytes)): + headers = {} + body = content + if isinstance(content, str): + headers["Content-Type"] = "text/plain" + if body: + headers["Content-Length"] = str(len(body)) + return headers, body + if any(hasattr(content, attr) for attr in ["read", "__iter__", "__aiter__"]): + return headers, content + raise TypeError( + "Unexpected type for 'content': '{}'. ".format(type(content)) + + "We expect 'content' to either be str, bytes, a open file-like object or an iterable/asynciterable." + ) + + +def set_json_body(json: Any) -> Tuple[Dict[str, str], Any]: + headers = {"Content-Type": "application/json"} + if hasattr(json, "read"): + content_headers, body = set_content_body(json) + headers.update(content_headers) + else: + body = dumps(json, cls=AzureJSONEncoder) + headers.update({"Content-Length": str(len(body))}) + return headers, body + + +def lookup_encoding(encoding: str) -> bool: + # including check for whether encoding is known taken from httpx + try: + codecs.lookup(encoding) + return True + except LookupError: + return False + + +def get_charset_encoding(response) -> Optional[str]: + content_type = response.headers.get("Content-Type") + + if not content_type: + return None + # https://peps.python.org/pep-0594/#cgi + m = email.message.Message() + m["content-type"] = content_type + encoding = cast(str, m.get_param("charset")) # -> utf-8 + if encoding is None or not lookup_encoding(encoding): + return None + return encoding + + +def decode_to_text(encoding: Optional[str], content: bytes) -> str: + if not content: + return "" + if encoding == "utf-8": + encoding = "utf-8-sig" + if encoding: + return content.decode(encoding) + return codecs.getincrementaldecoder("utf-8-sig")(errors="replace").decode(content) + + +class HttpRequestBackcompatMixin: + def __getattr__(self, attr: str) -> Any: + backcompat_attrs = [ + "files", + "data", + "multipart_mixed_info", + "query", + "body", + "format_parameters", + "set_streamed_data_body", + "set_text_body", + "set_xml_body", + "set_json_body", + "set_formdata_body", + "set_bytes_body", + "set_multipart_mixed", + "prepare_multipart_body", + "serialize", + ] + attr = _pad_attr_name(attr, backcompat_attrs) + return self.__getattribute__(attr) + + def __setattr__(self, attr: str, value: Any) -> None: + backcompat_attrs = [ + "multipart_mixed_info", + "files", + "data", + "body", + ] + attr = _pad_attr_name(attr, backcompat_attrs) + super(HttpRequestBackcompatMixin, self).__setattr__(attr, value) + + @property + def _multipart_mixed_info(self) -> Optional[Tuple[Sequence[Any], Sequence[Any], str, Dict[str, Any]]]: + """DEPRECATED: Information used to make multipart mixed requests. + This is deprecated and will be removed in a later release. + + :rtype: tuple + :return: (requests, policies, boundary, kwargs) + """ + try: + return self._multipart_mixed_info_val + except AttributeError: + return None + + @_multipart_mixed_info.setter + def _multipart_mixed_info(self, val: Optional[Tuple[Sequence[Any], Sequence[Any], str, Dict[str, Any]]]): + """DEPRECATED: Set information to make multipart mixed requests. + This is deprecated and will be removed in a later release. + + :param tuple val: (requests, policies, boundary, kwargs) + """ + self._multipart_mixed_info_val = val + + @property + def _query(self) -> Dict[str, Any]: + """DEPRECATED: Query parameters passed in by user + This is deprecated and will be removed in a later release. + + :rtype: dict + :return: Query parameters + """ + query = urlparse(self.url).query + if query: + return {p[0]: p[-1] for p in [p.partition("=") for p in query.split("&")]} + return {} + + @property + def _body(self) -> DataType: + """DEPRECATED: Body of the request. You should use the `content` property instead + This is deprecated and will be removed in a later release. + + :rtype: bytes + :return: Body of the request + """ + return self._data + + @_body.setter + def _body(self, val: DataType) -> None: + """DEPRECATED: Set the body of the request + This is deprecated and will be removed in a later release. + + :param bytes val: Body of the request + """ + self._data = val + + def _format_parameters(self, params: MutableMapping[str, str]) -> None: + """DEPRECATED: Format the query parameters + This is deprecated and will be removed in a later release. + You should pass the query parameters through the kwarg `params` + instead. + + :param dict params: Query parameters + """ + _format_parameters_helper(self, params) + + def _set_streamed_data_body(self, data): + """DEPRECATED: Set the streamed request body. + This is deprecated and will be removed in a later release. + You should pass your stream content through the `content` kwarg instead + + :param data: Streamed data + :type data: bytes or iterable + """ + if not isinstance(data, binary_type) and not any( + hasattr(data, attr) for attr in ["read", "__iter__", "__aiter__"] + ): + raise TypeError("A streamable data source must be an open file-like object or iterable.") + headers = self._set_body(content=data) + self._files = None + self.headers.update(headers) + + def _set_text_body(self, data): + """DEPRECATED: Set the text body + This is deprecated and will be removed in a later release. + You should pass your text content through the `content` kwarg instead + + :param str data: Text data + """ + headers = self._set_body(content=data) + self.headers.update(headers) + self._files = None + + def _set_xml_body(self, data): + """DEPRECATED: Set the xml body. + This is deprecated and will be removed in a later release. + You should pass your xml content through the `content` kwarg instead + + :param data: XML data + :type data: xml.etree.ElementTree.Element + """ + headers = self._set_body(content=data) + self.headers.update(headers) + self._files = None + + def _set_json_body(self, data): + """DEPRECATED: Set the json request body. + This is deprecated and will be removed in a later release. + You should pass your json content through the `json` kwarg instead + + :param data: JSON data + :type data: dict + """ + headers = self._set_body(json=data) + self.headers.update(headers) + self._files = None + + def _set_formdata_body(self, data=None): + """DEPRECATED: Set the formrequest body. + This is deprecated and will be removed in a later release. + You should pass your stream content through the `files` kwarg instead + + :param data: Form data + :type data: dict + """ + if data is None: + data = {} + content_type = self.headers.pop("Content-Type", None) if self.headers else None + + if content_type and content_type.lower() == "application/x-www-form-urlencoded": + headers = self._set_body(data=data) + self._files = None + else: # Assume "multipart/form-data" + headers = self._set_body(files=data) + self._data = None + self.headers.update(headers) + + def _set_bytes_body(self, data): + """DEPRECATED: Set the bytes request body. + This is deprecated and will be removed in a later release. + You should pass your bytes content through the `content` kwarg instead + + :param bytes data: Bytes data + """ + headers = self._set_body(content=data) + # we don't want default Content-Type + # in 2.7, byte strings are still strings, so they get set with text/plain content type + + headers.pop("Content-Type", None) + self.headers.update(headers) + self._files = None + + def _set_multipart_mixed(self, *requests: HttpRequest, **kwargs: Any) -> None: + """DEPRECATED: Set the multipart mixed info. + This is deprecated and will be removed in a later release. + + :param requests: Requests to be sent in the multipart request + :type requests: list[HttpRequest] + """ + self.multipart_mixed_info: Tuple[Sequence[HttpRequest], Sequence[Any], str, Dict[str, Any]] = ( + requests, + kwargs.pop("policies", []), + kwargs.pop("boundary", None), + kwargs, + ) + + def _prepare_multipart_body(self, content_index=0): + """DEPRECATED: Prepare your request body for multipart requests. + This is deprecated and will be removed in a later release. + + :param int content_index: The index of the request to be sent in the multipart request + :returns: The updated index after all parts in this request have been added. + :rtype: int + """ + return _prepare_multipart_body_helper(self, content_index) + + def _serialize(self): + """DEPRECATED: Serialize this request using application/http spec. + This is deprecated and will be removed in a later release. + + :rtype: bytes + :return: The serialized request + """ + return _serialize_request(self) + + def _add_backcompat_properties(self, request, memo): + """While deepcopying, we also need to add the private backcompat attrs. + + :param HttpRequest request: The request to copy from + :param dict memo: The memo dict used by deepcopy + """ + request._multipart_mixed_info = copy.deepcopy( # pylint: disable=protected-access + self._multipart_mixed_info, memo + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_http_response_impl.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_http_response_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..8754985820ba8ce7e48e28406becb1ac304c5a19 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_http_response_impl.py @@ -0,0 +1,477 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from json import loads +from typing import Any, Optional, Iterator, MutableMapping, Callable +from http.client import HTTPResponse as _HTTPResponse +from ._helpers import ( + get_charset_encoding, + decode_to_text, +) +from ..exceptions import ( + HttpResponseError, + ResponseNotReadError, + StreamConsumedError, + StreamClosedError, +) +from ._rest_py3 import ( + _HttpResponseBase, + HttpResponse as _HttpResponse, + HttpRequest as _HttpRequest, +) +from ..utils._utils import case_insensitive_dict +from ..utils._pipeline_transport_rest_shared import ( + _pad_attr_name, + BytesIOSocket, + _decode_parts_helper, + _get_raw_parts_helper, + _parts_helper, +) + + +class _HttpResponseBackcompatMixinBase: + """Base Backcompat mixin for responses. + + This mixin is used by both sync and async HttpResponse + backcompat mixins. + """ + + def __getattr__(self, attr): + backcompat_attrs = [ + "body", + "internal_response", + "block_size", + "stream_download", + ] + attr = _pad_attr_name(attr, backcompat_attrs) + return self.__getattribute__(attr) + + def __setattr__(self, attr, value): + backcompat_attrs = [ + "block_size", + "internal_response", + "request", + "status_code", + "headers", + "reason", + "content_type", + "stream_download", + ] + attr = _pad_attr_name(attr, backcompat_attrs) + super(_HttpResponseBackcompatMixinBase, self).__setattr__(attr, value) + + def _body(self): + """DEPRECATED: Get the response body. + This is deprecated and will be removed in a later release. + You should get it through the `content` property instead + + :return: The response body. + :rtype: bytes + """ + self.read() + return self.content # pylint: disable=no-member + + def _decode_parts(self, message, http_response_type, requests): + """Helper for _decode_parts. + + Rebuild an HTTP response from pure string. + + :param message: The body as an email.Message type + :type message: ~email.message.Message + :param http_response_type: The type of response to build + :type http_response_type: type + :param requests: A list of requests to process + :type requests: list[~azure.core.rest.HttpRequest] + :return: A list of responses + :rtype: list[~azure.core.rest.HttpResponse] + """ + + def _deserialize_response(http_response_as_bytes, http_request, http_response_type): + local_socket = BytesIOSocket(http_response_as_bytes) + response = _HTTPResponse(local_socket, method=http_request.method) + response.begin() + return http_response_type(request=http_request, internal_response=response) + + return _decode_parts_helper( + self, + message, + http_response_type or RestHttpClientTransportResponse, + requests, + _deserialize_response, + ) + + def _get_raw_parts(self, http_response_type=None): + """Helper for get_raw_parts + + Assuming this body is multipart, return the iterator or parts. + + If parts are application/http use http_response_type or HttpClientTransportResponse + as envelope. + + :param http_response_type: The type of response to build + :type http_response_type: type + :return: An iterator of responses + :rtype: Iterator[~azure.core.rest.HttpResponse] + """ + return _get_raw_parts_helper(self, http_response_type or RestHttpClientTransportResponse) + + def _stream_download(self, pipeline, **kwargs): + """DEPRECATED: Generator for streaming request body data. + This is deprecated and will be removed in a later release. + You should use `iter_bytes` or `iter_raw` instead. + + :param pipeline: The pipeline object + :type pipeline: ~azure.core.pipeline.Pipeline + :return: An iterator for streaming request body data. + :rtype: iterator[bytes] + """ + return self._stream_download_generator(pipeline, self, **kwargs) + + +class HttpResponseBackcompatMixin(_HttpResponseBackcompatMixinBase): + """Backcompat mixin for sync HttpResponses""" + + def __getattr__(self, attr): + backcompat_attrs = ["parts"] + attr = _pad_attr_name(attr, backcompat_attrs) + return super(HttpResponseBackcompatMixin, self).__getattr__(attr) + + def parts(self): + """DEPRECATED: Assuming the content-type is multipart/mixed, will return the parts as an async iterator. + This is deprecated and will be removed in a later release. + + :rtype: Iterator + :return: The parts of the response + :raises ValueError: If the content is not multipart/mixed + """ + return _parts_helper(self) + + +class _HttpResponseBaseImpl( + _HttpResponseBase, _HttpResponseBackcompatMixinBase +): # pylint: disable=too-many-instance-attributes + """Base Implementation class for azure.core.rest.HttpRespone and azure.core.rest.AsyncHttpResponse + + Since the rest responses are abstract base classes, we need to implement them for each of our transport + responses. This is the base implementation class shared by HttpResponseImpl and AsyncHttpResponseImpl. + The transport responses will be built on top of HttpResponseImpl and AsyncHttpResponseImpl + + :keyword request: The request that led to the response + :type request: ~azure.core.rest.HttpRequest + :keyword any internal_response: The response we get directly from the transport. For example, for our requests + transport, this will be a requests.Response. + :keyword optional[int] block_size: The block size we are using in our transport + :keyword int status_code: The status code of the response + :keyword str reason: The HTTP reason + :keyword str content_type: The content type of the response + :keyword MutableMapping[str, str] headers: The response headers + :keyword Callable stream_download_generator: The stream download generator that we use to stream the response. + """ + + def __init__(self, **kwargs) -> None: + super(_HttpResponseBaseImpl, self).__init__() + self._request = kwargs.pop("request") + self._internal_response = kwargs.pop("internal_response") + self._block_size: int = kwargs.pop("block_size", None) or 4096 + self._status_code: int = kwargs.pop("status_code") + self._reason: str = kwargs.pop("reason") + self._content_type: str = kwargs.pop("content_type") + self._headers: MutableMapping[str, str] = kwargs.pop("headers") + self._stream_download_generator: Callable = kwargs.pop("stream_download_generator") + self._is_closed = False + self._is_stream_consumed = False + self._json = None # this is filled in ContentDecodePolicy, when we deserialize + self._content: Optional[bytes] = None + self._text: Optional[str] = None + + @property + def request(self) -> _HttpRequest: + """The request that resulted in this response. + + :rtype: ~azure.core.rest.HttpRequest + :return: The request that resulted in this response. + """ + return self._request + + @property + def url(self) -> str: + """The URL that resulted in this response. + + :rtype: str + :return: The URL that resulted in this response. + """ + return self.request.url + + @property + def is_closed(self) -> bool: + """Whether the network connection has been closed yet. + + :rtype: bool + :return: Whether the network connection has been closed yet. + """ + return self._is_closed + + @property + def is_stream_consumed(self) -> bool: + """Whether the stream has been consumed. + + :rtype: bool + :return: Whether the stream has been consumed. + """ + return self._is_stream_consumed + + @property + def status_code(self) -> int: + """The status code of this response. + + :rtype: int + :return: The status code of this response. + """ + return self._status_code + + @property + def headers(self) -> MutableMapping[str, str]: + """The response headers. + + :rtype: MutableMapping[str, str] + :return: The response headers. + """ + return self._headers + + @property + def content_type(self) -> Optional[str]: + """The content type of the response. + + :rtype: optional[str] + :return: The content type of the response. + """ + return self._content_type + + @property + def reason(self) -> str: + """The reason phrase for this response. + + :rtype: str + :return: The reason phrase for this response. + """ + return self._reason + + @property + def encoding(self) -> Optional[str]: + """Returns the response encoding. + + :return: The response encoding. We either return the encoding set by the user, + or try extracting the encoding from the response's content type. If all fails, + we return `None`. + :rtype: optional[str] + """ + try: + return self._encoding + except AttributeError: + self._encoding: Optional[str] = get_charset_encoding(self) + return self._encoding + + @encoding.setter + def encoding(self, value: str) -> None: + """Sets the response encoding. + + :param str value: Sets the response encoding. + """ + self._encoding = value + self._text = None # clear text cache + self._json = None # clear json cache as well + + def text(self, encoding: Optional[str] = None) -> str: + """Returns the response body as a string + + :param optional[str] encoding: The encoding you want to decode the text with. Can + also be set independently through our encoding property + :return: The response's content decoded as a string. + :rtype: str + """ + if encoding: + return decode_to_text(encoding, self.content) + if self._text: + return self._text + self._text = decode_to_text(self.encoding, self.content) + return self._text + + def json(self) -> Any: + """Returns the whole body as a json object. + + :return: The JSON deserialized response body + :rtype: any + :raises json.decoder.JSONDecodeError or ValueError (in python 2.7) if object is not JSON decodable: + """ + # this will trigger errors if response is not read in + self.content # pylint: disable=pointless-statement + if not self._json: + self._json = loads(self.text()) + return self._json + + def _stream_download_check(self): + if self.is_stream_consumed: + raise StreamConsumedError(self) + if self.is_closed: + raise StreamClosedError(self) + + self._is_stream_consumed = True + + def raise_for_status(self) -> None: + """Raises an HttpResponseError if the response has an error status code. + + If response is good, does nothing. + """ + if self.status_code >= 400: + raise HttpResponseError(response=self) + + @property + def content(self) -> bytes: + """Return the response's content in bytes. + + :return: The response's content in bytes. + :rtype: bytes + """ + if self._content is None: + raise ResponseNotReadError(self) + return self._content + + def __repr__(self) -> str: + content_type_str = ", Content-Type: {}".format(self.content_type) if self.content_type else "" + return "".format(self.status_code, self.reason, content_type_str) + + +class HttpResponseImpl(_HttpResponseBaseImpl, _HttpResponse, HttpResponseBackcompatMixin): + """HttpResponseImpl built on top of our HttpResponse protocol class. + + Since ~azure.core.rest.HttpResponse is an abstract base class, we need to + implement HttpResponse for each of our transports. This is an implementation + that each of the sync transport responses can be built on. + + :keyword request: The request that led to the response + :type request: ~azure.core.rest.HttpRequest + :keyword any internal_response: The response we get directly from the transport. For example, for our requests + transport, this will be a requests.Response. + :keyword optional[int] block_size: The block size we are using in our transport + :keyword int status_code: The status code of the response + :keyword str reason: The HTTP reason + :keyword str content_type: The content type of the response + :keyword MutableMapping[str, str] headers: The response headers + :keyword Callable stream_download_generator: The stream download generator that we use to stream the response. + """ + + def __enter__(self) -> "HttpResponseImpl": + return self + + def close(self) -> None: + if not self.is_closed: + self._is_closed = True + self._internal_response.close() + + def __exit__(self, *args) -> None: + self.close() + + def _set_read_checks(self): + self._is_stream_consumed = True + self.close() + + def read(self) -> bytes: + """Read the response's bytes. + + :return: The response's bytes + :rtype: bytes + """ + if self._content is None: + self._content = b"".join(self.iter_bytes()) + self._set_read_checks() + return self.content + + def iter_bytes(self, **kwargs) -> Iterator[bytes]: + """Iterates over the response's bytes. Will decompress in the process. + + :return: An iterator of bytes from the response + :rtype: Iterator[str] + """ + if self._content is not None: + chunk_size = self._block_size + for i in range(0, len(self.content), chunk_size): + yield self.content[i : i + chunk_size] + else: + self._stream_download_check() + for part in self._stream_download_generator( + response=self, + pipeline=None, + decompress=True, + ): + yield part + self.close() + + def iter_raw(self, **kwargs) -> Iterator[bytes]: + """Iterates over the response's bytes. Will not decompress in the process. + + :return: An iterator of bytes from the response + :rtype: Iterator[str] + """ + self._stream_download_check() + for part in self._stream_download_generator(response=self, pipeline=None, decompress=False): + yield part + self.close() + + +class _RestHttpClientTransportResponseBackcompatBaseMixin(_HttpResponseBackcompatMixinBase): + def body(self): + if self._content is None: + self._content = self.internal_response.read() + return self.content + + +class _RestHttpClientTransportResponseBase(_HttpResponseBaseImpl, _RestHttpClientTransportResponseBackcompatBaseMixin): + def __init__(self, **kwargs): + internal_response = kwargs.pop("internal_response") + headers = case_insensitive_dict(internal_response.getheaders()) + super(_RestHttpClientTransportResponseBase, self).__init__( + internal_response=internal_response, + status_code=internal_response.status, + reason=internal_response.reason, + headers=headers, + content_type=headers.get("Content-Type"), + stream_download_generator=None, + **kwargs + ) + + +class RestHttpClientTransportResponse(_RestHttpClientTransportResponseBase, HttpResponseImpl): + """Create a Rest HTTPResponse from an http.client response.""" + + def iter_bytes(self, **kwargs): + raise TypeError("We do not support iter_bytes for this transport response") + + def iter_raw(self, **kwargs): + raise TypeError("We do not support iter_raw for this transport response") + + def read(self): + if self._content is None: + self._content = self._internal_response.read() + return self._content diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_http_response_impl_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_http_response_impl_async.py new file mode 100644 index 0000000000000000000000000000000000000000..e582a103dba4f0a57d99d261f85ef5057b959388 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_http_response_impl_async.py @@ -0,0 +1,155 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterator, Optional, Type +from types import TracebackType +from ._rest_py3 import AsyncHttpResponse as _AsyncHttpResponse +from ._http_response_impl import ( + _HttpResponseBaseImpl, + _HttpResponseBackcompatMixinBase, + _RestHttpClientTransportResponseBase, +) +from ..utils._pipeline_transport_rest_shared import _pad_attr_name +from ..utils._pipeline_transport_rest_shared_async import _PartGenerator + + +class AsyncHttpResponseBackcompatMixin(_HttpResponseBackcompatMixinBase): + """Backcompat mixin for async responses""" + + def __getattr__(self, attr): + backcompat_attrs = ["parts"] + attr = _pad_attr_name(attr, backcompat_attrs) + return super().__getattr__(attr) + + def parts(self): + """DEPRECATED: Assuming the content-type is multipart/mixed, will return the parts as an async iterator. + This is deprecated and will be removed in a later release. + :rtype: AsyncIterator + :return: The parts of the response + :raises ValueError: If the content is not multipart/mixed + """ + if not self.content_type or not self.content_type.startswith("multipart/mixed"): + raise ValueError("You can't get parts if the response is not multipart/mixed") + + return _PartGenerator(self, default_http_response_type=RestAsyncHttpClientTransportResponse) + + +class AsyncHttpResponseImpl(_HttpResponseBaseImpl, _AsyncHttpResponse, AsyncHttpResponseBackcompatMixin): + """AsyncHttpResponseImpl built on top of our HttpResponse protocol class. + + Since ~azure.core.rest.AsyncHttpResponse is an abstract base class, we need to + implement HttpResponse for each of our transports. This is an implementation + that each of the sync transport responses can be built on. + + :keyword request: The request that led to the response + :type request: ~azure.core.rest.HttpRequest + :keyword any internal_response: The response we get directly from the transport. For example, for our requests + transport, this will be a requests.Response. + :keyword optional[int] block_size: The block size we are using in our transport + :keyword int status_code: The status code of the response + :keyword str reason: The HTTP reason + :keyword str content_type: The content type of the response + :keyword MutableMapping[str, str] headers: The response headers + :keyword Callable stream_download_generator: The stream download generator that we use to stream the response. + """ + + async def _set_read_checks(self): + self._is_stream_consumed = True + await self.close() + + async def read(self) -> bytes: + """Read the response's bytes into memory. + + :return: The response's bytes + :rtype: bytes + """ + if self._content is None: + parts = [] + async for part in self.iter_bytes(): + parts.append(part) + self._content = b"".join(parts) + await self._set_read_checks() + return self._content + + async def iter_raw(self, **kwargs: Any) -> AsyncIterator[bytes]: + """Asynchronously iterates over the response's bytes. Will not decompress in the process + :return: An async iterator of bytes from the response + :rtype: AsyncIterator[bytes] + """ + self._stream_download_check() + async for part in self._stream_download_generator(response=self, pipeline=None, decompress=False): + yield part + await self.close() + + async def iter_bytes(self, **kwargs: Any) -> AsyncIterator[bytes]: + """Asynchronously iterates over the response's bytes. Will decompress in the process + :return: An async iterator of bytes from the response + :rtype: AsyncIterator[bytes] + """ + if self._content is not None: + for i in range(0, len(self.content), self._block_size): + yield self.content[i : i + self._block_size] + else: + self._stream_download_check() + async for part in self._stream_download_generator(response=self, pipeline=None, decompress=True): + yield part + await self.close() + + async def close(self) -> None: + """Close the response. + + :return: None + :rtype: None + """ + if not self.is_closed: + self._is_closed = True + await self._internal_response.close() + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ) -> None: + await self.close() + + def __repr__(self) -> str: + content_type_str = ", Content-Type: {}".format(self.content_type) if self.content_type else "" + return "".format(self.status_code, self.reason, content_type_str) + + +class RestAsyncHttpClientTransportResponse(_RestHttpClientTransportResponseBase, AsyncHttpResponseImpl): + """Create a Rest HTTPResponse from an http.client response.""" + + async def iter_bytes(self, **kwargs): + raise TypeError("We do not support iter_bytes for this transport response") + + async def iter_raw(self, **kwargs): + raise TypeError("We do not support iter_raw for this transport response") + + async def read(self): + if self._content is None: + self._content = self._internal_response.read() + return self._content diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_requests_asyncio.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_requests_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..35e896676e42022f1943ce60117e7255dba0f60b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_requests_asyncio.py @@ -0,0 +1,47 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import asyncio +from ._http_response_impl_async import AsyncHttpResponseImpl +from ._requests_basic import _RestRequestsTransportResponseBase +from ..pipeline.transport._requests_asyncio import AsyncioStreamDownloadGenerator + + +class RestAsyncioRequestsTransportResponse(AsyncHttpResponseImpl, _RestRequestsTransportResponseBase): # type: ignore + """Asynchronous streaming of data from the response.""" + + def __init__(self, **kwargs): + super().__init__(stream_download_generator=AsyncioStreamDownloadGenerator, **kwargs) + + async def close(self) -> None: + """Close the response. + + :return: None + :rtype: None + """ + if not self.is_closed: + self._is_closed = True + self._internal_response.close() + await asyncio.sleep(0) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_requests_basic.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_requests_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..4934619b13b069f6bdf0a8a63da8568e8fb34b75 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_requests_basic.py @@ -0,0 +1,102 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import collections.abc as collections +from requests.structures import CaseInsensitiveDict # pylint: disable=networking-import-outside-azure-core-transport + +from ._http_response_impl import ( + _HttpResponseBaseImpl, + HttpResponseImpl, + _HttpResponseBackcompatMixinBase, +) +from ..pipeline.transport._requests_basic import StreamDownloadGenerator + + +class _ItemsView(collections.ItemsView): + def __contains__(self, item): + if not (isinstance(item, (list, tuple)) and len(item) == 2): + return False # requests raises here, we just return False + for k, v in self.__iter__(): + if item[0].lower() == k.lower() and item[1] == v: + return True + return False + + def __repr__(self): + return "ItemsView({})".format(dict(self.__iter__())) + + +class _CaseInsensitiveDict(CaseInsensitiveDict): + """Overriding default requests dict so we can unify + to not raise if users pass in incorrect items to contains. + Instead, we return False + """ + + def items(self): + """Return a new view of the dictionary's items. + + :rtype: ~collections.abc.ItemsView[str, str] + :returns: a view object that displays a list of (key, value) tuple pairs + """ + return _ItemsView(self) + + +class _RestRequestsTransportResponseBaseMixin(_HttpResponseBackcompatMixinBase): + """Backcompat mixin for the sync and async requests responses + + Overriding the default mixin behavior here because we need to synchronously + read the response's content for the async requests responses + """ + + def _body(self): + # Since requests is not an async library, for backcompat, users should + # be able to access the body directly without loading it first (like we have to do + # in aiohttp). So here, we set self._content to self._internal_response.content, + # which is similar to read, without the async call. + if self._content is None: + self._content = self._internal_response.content + return self._content + + +class _RestRequestsTransportResponseBase(_HttpResponseBaseImpl, _RestRequestsTransportResponseBaseMixin): + def __init__(self, **kwargs): + internal_response = kwargs.pop("internal_response") + content = None + if internal_response._content_consumed: + content = internal_response.content + headers = _CaseInsensitiveDict(internal_response.headers) + super(_RestRequestsTransportResponseBase, self).__init__( + internal_response=internal_response, + status_code=internal_response.status_code, + headers=headers, + reason=internal_response.reason, + content_type=headers.get("content-type"), + content=content, + **kwargs + ) + + +class RestRequestsTransportResponse(HttpResponseImpl, _RestRequestsTransportResponseBase): + def __init__(self, **kwargs): + super(RestRequestsTransportResponse, self).__init__(stream_download_generator=StreamDownloadGenerator, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_requests_trio.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_requests_trio.py new file mode 100644 index 0000000000000000000000000000000000000000..bad6e85b13ec4764a67b22870ce19f315b087d19 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_requests_trio.py @@ -0,0 +1,42 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import trio # pylint: disable=networking-import-outside-azure-core-transport +from ._http_response_impl_async import AsyncHttpResponseImpl +from ._requests_basic import _RestRequestsTransportResponseBase +from ..pipeline.transport._requests_trio import TrioStreamDownloadGenerator + + +class RestTrioRequestsTransportResponse(AsyncHttpResponseImpl, _RestRequestsTransportResponseBase): # type: ignore + """Asynchronous streaming of data from the response.""" + + def __init__(self, **kwargs): + super().__init__(stream_download_generator=TrioStreamDownloadGenerator, **kwargs) + + async def close(self) -> None: + if not self.is_closed: + self._is_closed = True + self._internal_response.close() + await trio.sleep(0) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_rest_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_rest_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..50da91e366b0080afebdc638f235d55bc2a798c9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/rest/_rest_py3.py @@ -0,0 +1,422 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import abc +import copy +from typing import ( + Any, + AsyncIterable, + AsyncIterator, + Iterable, + Iterator, + Optional, + Union, + MutableMapping, + Dict, + AsyncContextManager, +) + +from ..utils._utils import case_insensitive_dict + +from ._helpers import ( + ParamsType, + FilesType, + set_json_body, + set_multipart_body, + set_urlencoded_body, + _format_parameters_helper, + HttpRequestBackcompatMixin, + set_content_body, +) + +ContentType = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] + +################################## CLASSES ###################################### + + +class HttpRequest(HttpRequestBackcompatMixin): + """An HTTP request. + + It should be passed to your client's `send_request` method. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest('GET', 'http://www.example.com') + + >>> response = client.send_request(request) + + + :param str method: HTTP method (GET, HEAD, etc.) + :param str url: The url for your request + :keyword mapping params: Query parameters to be mapped into your URL. Your input + should be a mapping of query name to query value(s). + :keyword mapping headers: HTTP headers you want in your request. Your input should + be a mapping of header name to header value. + :keyword any json: A JSON serializable object. We handle JSON-serialization for your + object, so use this for more complicated data structures than `data`. + :keyword content: Content you want in your request body. Think of it as the kwarg you should input + if your data doesn't fit into `json`, `data`, or `files`. Accepts a bytes type, or a generator + that yields bytes. + :paramtype content: str or bytes or iterable[bytes] or asynciterable[bytes] + :keyword dict data: Form data you want in your request body. Use for form-encoded data, i.e. + HTML forms. + :keyword mapping files: Files you want to in your request body. Use for uploading files with + multipart encoding. Your input should be a mapping of file name to file content. + Use the `data` kwarg in addition if you want to include non-file data files as part of your request. + :ivar str url: The URL this request is against. + :ivar str method: The method type of this request. + :ivar mapping headers: The HTTP headers you passed in to your request + :ivar any content: The content passed in for the request + """ + + def __init__( + self, + method: str, + url: str, + *, + params: Optional[ParamsType] = None, + headers: Optional[MutableMapping[str, str]] = None, + json: Any = None, + content: Optional[ContentType] = None, + data: Optional[Dict[str, Any]] = None, + files: Optional[FilesType] = None, + **kwargs: Any + ): + self.url = url + self.method = method + + if params: + _format_parameters_helper(self, params) + self._files = None + self._data: Any = None + + default_headers = self._set_body( + content=content, + data=data, + files=files, + json=json, + ) + self.headers: MutableMapping[str, str] = case_insensitive_dict(default_headers) + self.headers.update(headers or {}) + + if kwargs: + raise TypeError( + "You have passed in kwargs '{}' that are not valid kwargs.".format("', '".join(list(kwargs.keys()))) + ) + + def _set_body( + self, + content: Optional[ContentType] = None, + data: Optional[Dict[str, Any]] = None, + files: Optional[FilesType] = None, + json: Any = None, + ) -> MutableMapping[str, str]: + """Sets the body of the request, and returns the default headers. + + :param content: Content you want in your request body. + :type content: str or bytes or iterable[bytes] or asynciterable[bytes] + :param dict data: Form data you want in your request body. + :param dict files: Files you want to in your request body. + :param any json: A JSON serializable object. + :return: The default headers for the request + :rtype: MutableMapping[str, str] + """ + default_headers: MutableMapping[str, str] = {} + if data is not None and not isinstance(data, dict): + # should we warn? + content = data + if content is not None: + default_headers, self._data = set_content_body(content) + return default_headers + if json is not None: + default_headers, self._data = set_json_body(json) + return default_headers + if files: + default_headers, self._files = set_multipart_body(files) + if data: + default_headers, self._data = set_urlencoded_body(data, has_files=bool(files)) + return default_headers + + @property + def content(self) -> Any: + """Get's the request's content + + :return: The request's content + :rtype: any + """ + return self._data or self._files + + def __repr__(self) -> str: + return "".format(self.method, self.url) + + def __deepcopy__(self, memo: Optional[Dict[int, Any]] = None) -> "HttpRequest": + try: + request = HttpRequest( + method=self.method, + url=self.url, + headers=self.headers, + ) + request._data = copy.deepcopy(self._data, memo) + request._files = copy.deepcopy(self._files, memo) + self._add_backcompat_properties(request, memo) + return request + except (ValueError, TypeError): + return copy.copy(self) + + +class _HttpResponseBase(abc.ABC): + """Base abstract base class for HttpResponses.""" + + @property + @abc.abstractmethod + def request(self) -> HttpRequest: + """The request that resulted in this response. + + :rtype: ~azure.core.rest.HttpRequest + :return: The request that resulted in this response. + """ + + @property + @abc.abstractmethod + def status_code(self) -> int: + """The status code of this response. + + :rtype: int + :return: The status code of this response. + """ + + @property + @abc.abstractmethod + def headers(self) -> MutableMapping[str, str]: + """The response headers. Must be case-insensitive. + + :rtype: MutableMapping[str, str] + :return: The response headers. Must be case-insensitive. + """ + + @property + @abc.abstractmethod + def reason(self) -> str: + """The reason phrase for this response. + + :rtype: str + :return: The reason phrase for this response. + """ + + @property + @abc.abstractmethod + def content_type(self) -> Optional[str]: + """The content type of the response. + + :rtype: str + :return: The content type of the response. + """ + + @property + @abc.abstractmethod + def is_closed(self) -> bool: + """Whether the network connection has been closed yet. + + :rtype: bool + :return: Whether the network connection has been closed yet. + """ + + @property + @abc.abstractmethod + def is_stream_consumed(self) -> bool: + """Whether the stream has been consumed. + + :rtype: bool + :return: Whether the stream has been consumed. + """ + + @property + @abc.abstractmethod + def encoding(self) -> Optional[str]: + """Returns the response encoding. + + :return: The response encoding. We either return the encoding set by the user, + or try extracting the encoding from the response's content type. If all fails, + we return `None`. + :rtype: optional[str] + """ + + @encoding.setter + def encoding(self, value: Optional[str]) -> None: + """Sets the response encoding. + + :param optional[str] value: The encoding to set + """ + + @property + @abc.abstractmethod + def url(self) -> str: + """The URL that resulted in this response. + + :rtype: str + :return: The URL that resulted in this response. + """ + + @property + @abc.abstractmethod + def content(self) -> bytes: + """Return the response's content in bytes. + + :rtype: bytes + :return: The response's content in bytes. + """ + + @abc.abstractmethod + def text(self, encoding: Optional[str] = None) -> str: + """Returns the response body as a string. + + :param optional[str] encoding: The encoding you want to decode the text with. Can + also be set independently through our encoding property + :return: The response's content decoded as a string. + :rtype: str + """ + + @abc.abstractmethod + def json(self) -> Any: + """Returns the whole body as a json object. + + :return: The JSON deserialized response body + :rtype: any + :raises json.decoder.JSONDecodeError or ValueError (in python 2.7) if object is not JSON decodable: + """ + + @abc.abstractmethod + def raise_for_status(self) -> None: + """Raises an HttpResponseError if the response has an error status code. + + If response is good, does nothing. + + :raises ~azure.core.HttpResponseError if the object has an error status code.: + """ + + +class HttpResponse(_HttpResponseBase): + """Abstract base class for HTTP responses. + + Use this abstract base class to create your own transport responses. + + Responses implementing this ABC are returned from your client's `send_request` method + if you pass in an :class:`~azure.core.rest.HttpRequest` + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest('GET', 'http://www.example.com') + + >>> response = client.send_request(request) + + """ + + @abc.abstractmethod + def __enter__(self) -> "HttpResponse": + ... + + @abc.abstractmethod + def __exit__(self, *args: Any) -> None: + ... + + @abc.abstractmethod + def close(self) -> None: + ... + + @abc.abstractmethod + def read(self) -> bytes: + """Read the response's bytes. + + :return: The read in bytes + :rtype: bytes + """ + + @abc.abstractmethod + def iter_raw(self, **kwargs: Any) -> Iterator[bytes]: + """Iterates over the response's bytes. Will not decompress in the process. + + :return: An iterator of bytes from the response + :rtype: Iterator[str] + """ + + @abc.abstractmethod + def iter_bytes(self, **kwargs: Any) -> Iterator[bytes]: + """Iterates over the response's bytes. Will decompress in the process. + + :return: An iterator of bytes from the response + :rtype: Iterator[str] + """ + + def __repr__(self) -> str: + content_type_str = ", Content-Type: {}".format(self.content_type) if self.content_type else "" + return "".format(self.status_code, self.reason, content_type_str) + + +class AsyncHttpResponse(_HttpResponseBase, AsyncContextManager["AsyncHttpResponse"]): + """Abstract base class for Async HTTP responses. + + Use this abstract base class to create your own transport responses. + + Responses implementing this ABC are returned from your async client's `send_request` + method if you pass in an :class:`~azure.core.rest.HttpRequest` + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest('GET', 'http://www.example.com') + + >>> response = await client.send_request(request) + + """ + + @abc.abstractmethod + async def read(self) -> bytes: + """Read the response's bytes into memory. + + :return: The response's bytes + :rtype: bytes + """ + + @abc.abstractmethod + async def iter_raw(self, **kwargs: Any) -> AsyncIterator[bytes]: + """Asynchronously iterates over the response's bytes. Will not decompress in the process. + + :return: An async iterator of bytes from the response + :rtype: AsyncIterator[bytes] + """ + raise NotImplementedError() + # getting around mypy behavior, see https://github.com/python/mypy/issues/10732 + yield # pylint: disable=unreachable + + @abc.abstractmethod + async def iter_bytes(self, **kwargs: Any) -> AsyncIterator[bytes]: + """Asynchronously iterates over the response's bytes. Will decompress in the process. + + :return: An async iterator of bytes from the response + :rtype: AsyncIterator[bytes] + """ + raise NotImplementedError() + # getting around mypy behavior, see https://github.com/python/mypy/issues/10732 + yield # pylint: disable=unreachable + + @abc.abstractmethod + async def close(self) -> None: + ... diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ecf6fe6da8dfb427c162e9ec404f2ce8b401cde9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from azure.core.tracing._abstract_span import ( + AbstractSpan, + SpanKind, + HttpSpanMixin, + Link, +) + +__all__ = ["AbstractSpan", "SpanKind", "HttpSpanMixin", "Link"] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/_abstract_span.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/_abstract_span.py new file mode 100644 index 0000000000000000000000000000000000000000..0eb9055d998ea1f7a5d72ba0b79c33dc1cb4d6b3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/_abstract_span.py @@ -0,0 +1,307 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Protocol that defines what functions wrappers of tracing libraries should implement.""" +from __future__ import annotations +from enum import Enum +from urllib.parse import urlparse + +from typing import Any, Sequence, Optional, Union, Callable, Dict, Type, Generic, TypeVar +from types import TracebackType +from typing_extensions import Protocol, ContextManager, runtime_checkable +from azure.core.pipeline.transport import HttpRequest, HttpResponse, AsyncHttpResponse +from azure.core.rest import ( + HttpResponse as RestHttpResponse, + AsyncHttpResponse as AsyncRestHttpResponse, + HttpRequest as RestHttpRequest, +) + +HttpResponseType = Union[HttpResponse, AsyncHttpResponse, RestHttpResponse, AsyncRestHttpResponse] +HttpRequestType = Union[HttpRequest, RestHttpRequest] + +AttributeValue = Union[ + str, + bool, + int, + float, + Sequence[str], + Sequence[bool], + Sequence[int], + Sequence[float], +] +Attributes = Dict[str, AttributeValue] +SpanType = TypeVar("SpanType") + + +class SpanKind(Enum): + UNSPECIFIED = 1 + SERVER = 2 + CLIENT = 3 + PRODUCER = 4 + CONSUMER = 5 + INTERNAL = 6 + + +@runtime_checkable +class AbstractSpan(Protocol, Generic[SpanType]): + """Wraps a span from a distributed tracing implementation. + + If a span is given wraps the span. Else a new span is created. + The optional argument name is given to the new span. + + :param span: The span to wrap + :type span: Any + :param name: The name of the span + :type name: str + """ + + def __init__( # pylint: disable=super-init-not-called + self, span: Optional[SpanType] = None, name: Optional[str] = None, **kwargs: Any + ) -> None: + pass + + def span(self, name: str = "child_span", **kwargs: Any) -> AbstractSpan[SpanType]: + """ + Create a child span for the current span and append it to the child spans list. + The child span must be wrapped by an implementation of AbstractSpan + + :param name: The name of the child span + :type name: str + :return: The child span + :rtype: AbstractSpan + """ + ... + + @property + def kind(self) -> Optional[SpanKind]: + """Get the span kind of this span. + + :rtype: SpanKind + :return: The span kind of this span + """ + ... + + @kind.setter + def kind(self, value: SpanKind) -> None: + """Set the span kind of this span. + + :param value: The span kind of this span + :type value: SpanKind + """ + ... + + def __enter__(self) -> AbstractSpan[SpanType]: + """Start a span.""" + ... + + def __exit__( + self, + exception_type: Optional[Type[BaseException]], + exception_value: Optional[BaseException], + traceback: TracebackType, + ) -> None: + """Finish a span. + + :param exception_type: The type of the exception + :type exception_type: type + :param exception_value: The value of the exception + :type exception_value: Exception + :param traceback: The traceback of the exception + :type traceback: Traceback + """ + ... + + def start(self) -> None: + """Set the start time for a span.""" + ... + + def finish(self) -> None: + """Set the end time for a span.""" + ... + + def to_header(self) -> Dict[str, str]: + """Returns a dictionary with the header labels and values. + + :return: A dictionary with the header labels and values + :rtype: dict + """ + ... + + def add_attribute(self, key: str, value: Union[str, int]) -> None: + """ + Add attribute (key value pair) to the current span. + + :param key: The key of the key value pair + :type key: str + :param value: The value of the key value pair + :type value: Union[str, int] + """ + ... + + def set_http_attributes(self, request: HttpRequestType, response: Optional[HttpResponseType] = None) -> None: + """ + Add correct attributes for a http client span. + + :param request: The request made + :type request: azure.core.rest.HttpRequest + :param response: The response received by the server. Is None if no response received. + :type response: ~azure.core.pipeline.transport.HttpResponse or ~azure.core.pipeline.transport.AsyncHttpResponse + """ + ... + + def get_trace_parent(self) -> str: + """Return traceparent string. + + :return: a traceparent string + :rtype: str + """ + ... + + @property + def span_instance(self) -> SpanType: + """ + Returns the span the class is wrapping. + """ + ... + + @classmethod + def link(cls, traceparent: str, attributes: Optional[Attributes] = None) -> None: + """ + Given a traceparent, extracts the context and links the context to the current tracer. + + :param traceparent: A string representing a traceparent + :type traceparent: str + :param attributes: Any additional attributes that should be added to link + :type attributes: dict + """ + ... + + @classmethod + def link_from_headers(cls, headers: Dict[str, str], attributes: Optional[Attributes] = None) -> None: + """ + Given a dictionary, extracts the context and links the context to the current tracer. + + :param headers: A dictionary of the request header as key value pairs. + :type headers: dict + :param attributes: Any additional attributes that should be added to link + :type attributes: dict + """ + ... + + @classmethod + def get_current_span(cls) -> SpanType: + """ + Get the current span from the execution context. Return None otherwise. + + :return: The current span + :rtype: AbstractSpan + """ + ... + + @classmethod + def get_current_tracer(cls) -> Any: + """ + Get the current tracer from the execution context. Return None otherwise. + + :return: The current tracer + :rtype: Any + """ + ... + + @classmethod + def set_current_span(cls, span: SpanType) -> None: + """Set the given span as the current span in the execution context. + + :param span: The span to set as the current span + :type span: Any + """ + ... + + @classmethod + def set_current_tracer(cls, tracer: Any) -> None: + """Set the given tracer as the current tracer in the execution context. + + :param tracer: The tracer to set as the current tracer + :type tracer: Any + """ + ... + + @classmethod + def change_context(cls, span: SpanType) -> ContextManager[SpanType]: + """Change the context for the life of this context manager. + + :param span: The span to run in the new context + :type span: Any + :rtype: contextmanager + :return: A context manager that will run the given span in the new context + """ + ... + + @classmethod + def with_current_context(cls, func: Callable) -> Callable: + """Passes the current spans to the new context the function will be run in. + + :param func: The function that will be run in the new context + :type func: callable + :return: The target the pass in instead of the function + :rtype: callable + """ + ... + + +class HttpSpanMixin: + """Can be used to get HTTP span attributes settings for free.""" + + _SPAN_COMPONENT = "component" + _HTTP_USER_AGENT = "http.user_agent" + _HTTP_METHOD = "http.method" + _HTTP_URL = "http.url" + _HTTP_STATUS_CODE = "http.status_code" + _NET_PEER_NAME = "net.peer.name" + _NET_PEER_PORT = "net.peer.port" + + def set_http_attributes( + self: AbstractSpan, request: HttpRequestType, response: Optional[HttpResponseType] = None + ) -> None: + """ + Add correct attributes for a http client span. + + :param request: The request made + :type request: azure.core.rest.HttpRequest + :param response: The response received from the server. Is None if no response received. + :type response: ~azure.core.pipeline.transport.HttpResponse or ~azure.core.pipeline.transport.AsyncHttpResponse + """ + # Also see https://github.com/python/mypy/issues/5837 + self.kind = SpanKind.CLIENT + self.add_attribute(HttpSpanMixin._SPAN_COMPONENT, "http") + self.add_attribute(HttpSpanMixin._HTTP_METHOD, request.method) + self.add_attribute(HttpSpanMixin._HTTP_URL, request.url) + + parsed_url = urlparse(request.url) + if parsed_url.hostname: + self.add_attribute(HttpSpanMixin._NET_PEER_NAME, parsed_url.hostname) + if parsed_url.port and parsed_url.port not in [80, 443]: + self.add_attribute(HttpSpanMixin._NET_PEER_PORT, parsed_url.port) + + user_agent = request.headers.get("User-Agent") + if user_agent: + self.add_attribute(HttpSpanMixin._HTTP_USER_AGENT, user_agent) + if response and response.status_code: + self.add_attribute(HttpSpanMixin._HTTP_STATUS_CODE, response.status_code) + else: + self.add_attribute(HttpSpanMixin._HTTP_STATUS_CODE, 504) + + +class Link: + """ + This is a wrapper class to link the context to the current tracer. + :param headers: A dictionary of the request header as key value pairs. + :type headers: dict + :param attributes: Any additional attributes that should be added to link + :type attributes: dict + """ + + def __init__(self, headers: Dict[str, str], attributes: Optional[Attributes] = None) -> None: + self.headers = headers + self.attributes = attributes diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/common.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/common.py new file mode 100644 index 0000000000000000000000000000000000000000..4ce6e39de2ca5673ae5b20fec5ef2e2367bd13ee --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/common.py @@ -0,0 +1,108 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# -------------------------------------------------------------------------- +"""Common functions shared by both the sync and the async decorators.""" +from contextlib import contextmanager +from typing import Any, Optional, Callable, Type, Generator +import warnings + +from ._abstract_span import AbstractSpan +from ..settings import settings + + +__all__ = [ + "change_context", + "with_current_context", +] + + +def get_function_and_class_name(func: Callable, *args: object) -> str: + """ + Given a function and its unamed arguments, returns class_name.function_name. It assumes the first argument + is `self`. If there are no arguments then it only returns the function name. + + :param func: the function passed in + :type func: callable + :param args: List of arguments passed into the function + :type args: list + :return: The function name with the class name + :rtype: str + """ + try: + return func.__qualname__ + except AttributeError: + if args: + return "{}.{}".format(args[0].__class__.__name__, func.__name__) # pylint: disable=protected-access + return func.__name__ + + +@contextmanager +def change_context(span: Optional[AbstractSpan]) -> Generator: + """Execute this block inside the given context and restore it afterwards. + + This does not start and ends the span, but just make sure all code is executed within + that span. + + If span is None, no-op. + + :param span: A span + :type span: AbstractSpan + :rtype: contextmanager + :return: A context manager that will run the given span in the new context + """ + span_impl_type: Optional[Type[AbstractSpan]] = settings.tracing_implementation() + if span_impl_type is None or span is None: + yield + else: + try: + with span_impl_type.change_context(span): + yield + except AttributeError: + # This plugin does not support "change_context" + warnings.warn( + 'Your tracing plugin should be updated to support "change_context"', + DeprecationWarning, + ) + original_span = span_impl_type.get_current_span() + try: + span_impl_type.set_current_span(span) + yield + finally: + span_impl_type.set_current_span(original_span) + + +def with_current_context(func: Callable) -> Any: + """Passes the current spans to the new context the function will be run in. + + :param func: The function that will be run in the new context + :type func: callable + :return: The func wrapped with correct context + :rtype: callable + """ + span_impl_type: Optional[Type[AbstractSpan]] = settings.tracing_implementation() + if span_impl_type is None: + return func + + return span_impl_type.with_current_context(func) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/decorator.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..aee70d03e5b1fdf0464a50d6dcebbad67f5b133c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/decorator.py @@ -0,0 +1,93 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# -------------------------------------------------------------------------- +"""The decorator to apply if you want the given function traced.""" + +import functools + +from typing import Callable, Any, TypeVar, overload, Optional +from typing_extensions import ParamSpec +from .common import change_context, get_function_and_class_name +from . import SpanKind as _SpanKind +from ..settings import settings + + +P = ParamSpec("P") +T = TypeVar("T") + + +@overload +def distributed_trace(__func: Callable[P, T]) -> Callable[P, T]: + pass + + +@overload +def distributed_trace( # pylint:disable=function-redefined + **kwargs: Any, # pylint:disable=unused-argument +) -> Callable[[Callable[P, T]], Callable[P, T]]: + pass + + +def distributed_trace( + __func: Optional[Callable[P, T]] = None, **kwargs: Any +) -> Any: # pylint:disable=function-redefined + """Decorator to apply to function to get traced automatically. + + Span will use the func name or "name_of_span". + + :param callable func: A function to decorate + :keyword name_of_span: The span name to replace func name if necessary + :paramtype name_of_span: str + :keyword kind: The kind of the span. INTERNAL by default. + :paramtype kind: ~azure.core.tracing.SpanKind + """ + name_of_span = kwargs.pop("name_of_span", None) + tracing_attributes = kwargs.pop("tracing_attributes", {}) + kind = kwargs.pop("kind", _SpanKind.INTERNAL) + + def decorator(func: Callable[P, T]) -> Callable[P, T]: + @functools.wraps(func) + def wrapper_use_tracer(*args: Any, **kwargs: Any) -> T: + merge_span = kwargs.pop("merge_span", False) + passed_in_parent = kwargs.pop("parent_span", None) + + span_impl_type = settings.tracing_implementation() + if span_impl_type is None: + return func(*args, **kwargs) + + # Merge span is parameter is set, but only if no explicit parent are passed + if merge_span and not passed_in_parent: + return func(*args, **kwargs) + + with change_context(passed_in_parent): + name = name_of_span or get_function_and_class_name(func, *args) + with span_impl_type(name=name, kind=kind) as span: + for key, value in tracing_attributes.items(): + span.add_attribute(key, value) + return func(*args, **kwargs) + + return wrapper_use_tracer + + return decorator if __func is None else decorator(__func) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/decorator_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/decorator_async.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7d543cde2f0ff87ee85efb3a9f3eb4b66a1b39 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/decorator_async.py @@ -0,0 +1,92 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# -------------------------------------------------------------------------- +"""The decorator to apply if you want the given function traced.""" + +import functools + +from typing import Awaitable, Callable, Any, TypeVar, overload, Optional +from typing_extensions import ParamSpec +from .common import change_context, get_function_and_class_name +from . import SpanKind as _SpanKind +from ..settings import settings + +P = ParamSpec("P") +T = TypeVar("T") + + +@overload +def distributed_trace_async(__func: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]: + pass + + +@overload +def distributed_trace_async( # pylint:disable=function-redefined + **kwargs: Any, # pylint:disable=unused-argument +) -> Callable[[Callable[P, Awaitable[T]]], Callable[P, Awaitable[T]]]: + pass + + +def distributed_trace_async( # pylint:disable=function-redefined + __func: Optional[Callable[P, Awaitable[T]]] = None, **kwargs: Any +) -> Any: + """Decorator to apply to function to get traced automatically. + + Span will use the func name or "name_of_span". + + :param callable func: A function to decorate + :keyword name_of_span: The span name to replace func name if necessary + :paramtype name_of_span: str + :keyword kind: The kind of the span. INTERNAL by default. + :paramtype kind: ~azure.core.tracing.SpanKind + """ + name_of_span = kwargs.pop("name_of_span", None) + tracing_attributes = kwargs.pop("tracing_attributes", {}) + kind = kwargs.pop("kind", _SpanKind.INTERNAL) + + def decorator(func: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]: + @functools.wraps(func) + async def wrapper_use_tracer(*args: Any, **kwargs: Any) -> T: + merge_span = kwargs.pop("merge_span", False) + passed_in_parent = kwargs.pop("parent_span", None) + + span_impl_type = settings.tracing_implementation() + if span_impl_type is None: + return await func(*args, **kwargs) + + # Merge span is parameter is set, but only if no explicit parent are passed + if merge_span and not passed_in_parent: + return await func(*args, **kwargs) + + with change_context(passed_in_parent): + name = name_of_span or get_function_and_class_name(func, *args) + with span_impl_type(name=name, kind=kind) as span: + for key, value in tracing_attributes.items(): + span.add_attribute(key, value) + return await func(*args, **kwargs) + + return wrapper_use_tracer + + return decorator if __func is None else decorator(__func) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/ext/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/tracing/ext/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e06c1a3da7724c47ea241b388098e95347220c4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/__init__.py @@ -0,0 +1,35 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +""" + +This `utils` module provides functionality that is intended to be used by developers +building on top of `azure-core`. + +""" +from ._connection_string_parser import parse_connection_string +from ._utils import case_insensitive_dict, CaseInsensitiveDict + +__all__ = ["parse_connection_string", "case_insensitive_dict", "CaseInsensitiveDict"] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_connection_string_parser.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_connection_string_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..61494b487181460b4b40725eb9865bc388a3353e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_connection_string_parser.py @@ -0,0 +1,44 @@ +# coding=utf-8 +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from typing import Mapping + + +def parse_connection_string(conn_str: str, case_sensitive_keys: bool = False) -> Mapping[str, str]: + """Parses the connection string into a dict of its component parts, with the option of preserving case + of keys, and validates that each key in the connection string has a provided value. If case of keys + is not preserved (ie. `case_sensitive_keys=False`), then a dict with LOWERCASE KEYS will be returned. + + :param str conn_str: String with connection details provided by Azure services. + :param bool case_sensitive_keys: Indicates whether the casing of the keys will be preserved. When `False`(the + default), all keys will be lower-cased. If set to `True`, the original casing of the keys will be preserved. + :rtype: Mapping + :returns: Dict of connection string key/value pairs. + :raises: + ValueError: if each key in conn_str does not have a corresponding value and + for other bad formatting of connection strings - including duplicate + args, bad syntax, etc. + """ + + cs_args = [s.split("=", 1) for s in conn_str.strip().rstrip(";").split(";")] + if any(len(tup) != 2 or not all(tup) for tup in cs_args): + raise ValueError("Connection string is either blank or malformed.") + args_dict = dict(cs_args) + + if len(cs_args) != len(args_dict): + raise ValueError("Connection string is either blank or malformed.") + + if not case_sensitive_keys: + # if duplicate case insensitive keys are passed in, raise error + new_args_dict = {} + for key in args_dict.keys(): # pylint: disable=consider-using-dict-items + new_key = key.lower() + if new_key in new_args_dict: + raise ValueError("Duplicate key in connection string: {}".format(new_key)) + new_args_dict[new_key] = args_dict[key] + return new_args_dict + + return args_dict diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_messaging_shared.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_messaging_shared.py new file mode 100644 index 0000000000000000000000000000000000000000..e282db7ee8ac2a384d0c823f47d226fa52b4cdcd --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_messaging_shared.py @@ -0,0 +1,46 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +# ========================================================================== +# This file contains duplicate code that is shared with azure-eventgrid. +# Both the files should always be identical. +# ========================================================================== + + +import json + + +def _get_json_content(obj): + """Event mixin to have methods that are common to different Event types + like CloudEvent, EventGridEvent etc. + + :param obj: The object to get the JSON content from. + :type obj: any + :return: The JSON content of the object. + :rtype: dict + :raises ValueError if JSON content cannot be loaded from the object + """ + msg = "Failed to load JSON content from the object." + try: + # storage queue + return json.loads(obj.content) + except ValueError as err: + raise ValueError(msg) from err + except AttributeError: + # eventhubs + try: + return json.loads(next(obj.body))[0] + except KeyError: + # servicebus + return json.loads(next(obj.body)) + except ValueError as err: + raise ValueError(msg) from err + except: # pylint: disable=bare-except + try: + return json.loads(obj) + except ValueError as err: + raise ValueError(msg) from err diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_pipeline_transport_rest_shared.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_pipeline_transport_rest_shared.py new file mode 100644 index 0000000000000000000000000000000000000000..e8f50d596f4588eb6e1a4b4c032f502be7dfb636 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_pipeline_transport_rest_shared.py @@ -0,0 +1,420 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import absolute_import +from collections.abc import Mapping + +from io import BytesIO +from email.message import Message +from email.policy import HTTP +from email import message_from_bytes as message_parser +import os +from typing import ( + TYPE_CHECKING, + cast, + IO, + Union, + Tuple, + Optional, + Callable, + Type, + Iterator, + List, + Sequence, +) +from http.client import HTTPConnection +from urllib.parse import urlparse + +from ..pipeline import ( + PipelineRequest, + PipelineResponse, + PipelineContext, +) +from ..pipeline._tools import await_result as _await_result + +if TYPE_CHECKING: + # importing both the py3 RestHttpRequest and the fallback RestHttpRequest + from azure.core.rest._rest_py3 import HttpRequest as RestHttpRequestPy3 + from azure.core.pipeline.transport import ( + HttpRequest as PipelineTransportHttpRequest, + ) + + HTTPRequestType = Union[RestHttpRequestPy3, PipelineTransportHttpRequest] + from ..pipeline.policies import SansIOHTTPPolicy + from azure.core.pipeline.transport import ( # pylint: disable=non-abstract-transport-import + HttpResponse as PipelineTransportHttpResponse, + AioHttpTransportResponse as PipelineTransportAioHttpTransportResponse, + ) + from azure.core.pipeline.transport._base import ( + _HttpResponseBase as PipelineTransportHttpResponseBase, + ) + from azure.core.rest._helpers import FilesType, FileType, FileContent + +binary_type = str + + +class BytesIOSocket: + """Mocking the "makefile" of socket for HTTPResponse. + This can be used to create a http.client.HTTPResponse object + based on bytes and not a real socket. + + :param bytes bytes_data: The bytes to use to mock the socket. + """ + + def __init__(self, bytes_data): + self.bytes_data = bytes_data + + def makefile(self, *_): + return BytesIO(self.bytes_data) + + +def _format_parameters_helper(http_request, params): + """Helper for format_parameters. + + Format parameters into a valid query string. + It's assumed all parameters have already been quoted as + valid URL strings. + + :param http_request: The http request whose parameters + we are trying to format + :type http_request: any + :param dict params: A dictionary of parameters. + """ + query = urlparse(http_request.url).query + if query: + http_request.url = http_request.url.partition("?")[0] + existing_params = {p[0]: p[-1] for p in [p.partition("=") for p in query.split("&")]} + params.update(existing_params) + query_params = [] + for k, v in params.items(): + if isinstance(v, list): + for w in v: + if w is None: + raise ValueError("Query parameter {} cannot be None".format(k)) + query_params.append("{}={}".format(k, w)) + else: + if v is None: + raise ValueError("Query parameter {} cannot be None".format(k)) + query_params.append("{}={}".format(k, v)) + query = "?" + "&".join(query_params) + http_request.url = http_request.url + query + + +def _pad_attr_name(attr: str, backcompat_attrs: Sequence[str]) -> str: + """Pad hidden attributes so users can access them. + + Currently, for our backcompat attributes, we define them + as private, so they're hidden from intellisense and sphinx, + but still allow users to access them as public attributes + for backcompat purposes. This function is called so if + users access publicly call a private backcompat attribute, + we can return them the private variable in getattr + + :param str attr: The attribute name + :param list[str] backcompat_attrs: The list of backcompat attributes + :rtype: str + :return: The padded attribute name + """ + return "_{}".format(attr) if attr in backcompat_attrs else attr + + +def _prepare_multipart_body_helper(http_request: "HTTPRequestType", content_index: int = 0) -> int: + """Helper for prepare_multipart_body. + + Will prepare the body of this request according to the multipart information. + + This call assumes the on_request policies have been applied already in their + correct context (sync/async) + + Does nothing if "set_multipart_mixed" was never called. + :param http_request: The http request whose multipart body we are trying + to prepare + :type http_request: any + :param int content_index: The current index of parts within the batch message. + :returns: The updated index after all parts in this request have been added. + :rtype: int + """ + if not http_request.multipart_mixed_info: + return 0 + + requests: Sequence["HTTPRequestType"] = http_request.multipart_mixed_info[0] + boundary: Optional[str] = http_request.multipart_mixed_info[2] + + # Update the main request with the body + main_message = Message() + main_message.add_header("Content-Type", "multipart/mixed") + if boundary: + main_message.set_boundary(boundary) + + for req in requests: + part_message = Message() + if req.multipart_mixed_info: + content_index = req.prepare_multipart_body(content_index=content_index) + part_message.add_header("Content-Type", req.headers["Content-Type"]) + payload = req.serialize() + # We need to remove the ~HTTP/1.1 prefix along with the added content-length + payload = payload[payload.index(b"--") :] + else: + part_message.add_header("Content-Type", "application/http") + part_message.add_header("Content-Transfer-Encoding", "binary") + part_message.add_header("Content-ID", str(content_index)) + payload = req.serialize() + content_index += 1 + part_message.set_payload(payload) + main_message.attach(part_message) + + full_message = main_message.as_bytes(policy=HTTP) + # From "as_bytes" doc: + # Flattening the message may trigger changes to the EmailMessage if defaults need to be filled in to complete + # the transformation to a string (for example, MIME boundaries may be generated or modified). + # After this call, we know `get_boundary` will return a valid boundary and not None. Mypy doesn't know that. + final_boundary: str = cast(str, main_message.get_boundary()) + eol = b"\r\n" + _, _, body = full_message.split(eol, 2) + http_request.set_bytes_body(body) + http_request.headers["Content-Type"] = "multipart/mixed; boundary=" + final_boundary + return content_index + + +class _HTTPSerializer(HTTPConnection): + """Hacking the stdlib HTTPConnection to serialize HTTP request as strings.""" + + def __init__(self, *args, **kwargs): + self.buffer = b"" + kwargs.setdefault("host", "fakehost") + super(_HTTPSerializer, self).__init__(*args, **kwargs) + + def putheader(self, header, *values): + if header in ["Host", "Accept-Encoding"]: + return + super(_HTTPSerializer, self).putheader(header, *values) + + def send(self, data): + self.buffer += data + + +def _serialize_request(http_request: "HTTPRequestType") -> bytes: + """Helper for serialize. + + Serialize a request using the application/http spec/ + + :param http_request: The http request which we are trying + to serialize. + :type http_request: any + :rtype: bytes + :return: The serialized request + """ + if isinstance(http_request.body, dict): + raise TypeError("Cannot serialize an HTTPRequest with dict body.") + serializer = _HTTPSerializer() + serializer.request( + method=http_request.method, + url=http_request.url, + body=http_request.body, + headers=http_request.headers, + ) + return serializer.buffer + + +def _decode_parts_helper( + response: "PipelineTransportHttpResponseBase", + message: Message, + http_response_type: Type["PipelineTransportHttpResponseBase"], + requests: Sequence["PipelineTransportHttpRequest"], + deserialize_response: Callable, +) -> List["PipelineTransportHttpResponse"]: + """Helper for _decode_parts. + + Rebuild an HTTP response from pure string. + + :param response: The response to decode + :type response: ~azure.core.pipeline.transport.HttpResponse + :param message: The message to decode + :type message: ~email.message.Message + :param http_response_type: The type of response to return + :type http_response_type: ~azure.core.pipeline.transport.HttpResponse + :param requests: The requests that were batched together + :type requests: list[~azure.core.pipeline.transport.HttpRequest] + :param deserialize_response: The function to deserialize the response + :type deserialize_response: callable + :rtype: list[~azure.core.pipeline.transport.HttpResponse] + :return: The list of responses + """ + responses = [] + for index, raw_response in enumerate(message.get_payload()): + content_type = raw_response.get_content_type() + if content_type == "application/http": + try: + matching_request = requests[index] + except IndexError: + # If we have no matching request, this could mean that we had an empty batch. + # The request object is only needed to get the HTTP METHOD and to store in the response object, + # so let's just use the parent request so allow the rest of the deserialization to continue. + matching_request = response.request + responses.append( + deserialize_response( + raw_response.get_payload(decode=True), + matching_request, + http_response_type=http_response_type, + ) + ) + elif content_type == "multipart/mixed" and requests[index].multipart_mixed_info: + # The message batch contains one or more change sets + changeset_requests = requests[index].multipart_mixed_info[0] # type: ignore + changeset_responses = response._decode_parts( # pylint: disable=protected-access + raw_response, http_response_type, changeset_requests + ) + responses.extend(changeset_responses) + else: + raise ValueError("Multipart doesn't support part other than application/http for now") + return responses + + +def _get_raw_parts_helper(response, http_response_type: Type): + """Helper for _get_raw_parts + + Assuming this body is multipart, return the iterator or parts. + + If parts are application/http use http_response_type or HttpClientTransportResponse + as envelope. + + :param response: The response to decode + :type response: ~azure.core.pipeline.transport.HttpResponse + :param http_response_type: The type of response to return + :type http_response_type: any + :rtype: iterator[~azure.core.pipeline.transport.HttpResponse] + :return: The parts of the response + """ + body_as_bytes = response.body() + # In order to use email.message parser, I need full HTTP bytes. Faking something to make the parser happy + http_body = b"Content-Type: " + response.content_type.encode("ascii") + b"\r\n\r\n" + body_as_bytes + message: Message = message_parser(http_body) + requests = response.request.multipart_mixed_info[0] + return response._decode_parts(message, http_response_type, requests) # pylint: disable=protected-access + + +def _parts_helper( + response: "PipelineTransportHttpResponse", +) -> Iterator["PipelineTransportHttpResponse"]: + """Assuming the content-type is multipart/mixed, will return the parts as an iterator. + + :param response: The response to decode + :type response: ~azure.core.pipeline.transport.HttpResponse + :rtype: iterator[HttpResponse] + :return: The parts of the response + :raises ValueError: If the content is not multipart/mixed + """ + if not response.content_type or not response.content_type.startswith("multipart/mixed"): + raise ValueError("You can't get parts if the response is not multipart/mixed") + + responses = response._get_raw_parts() # pylint: disable=protected-access + if response.request.multipart_mixed_info: + policies: Sequence["SansIOHTTPPolicy"] = response.request.multipart_mixed_info[1] + + # Apply on_response concurrently to all requests + import concurrent.futures + + def parse_responses(response): + http_request = response.request + context = PipelineContext(None) + pipeline_request = PipelineRequest(http_request, context) + pipeline_response = PipelineResponse(http_request, response, context=context) + + for policy in policies: + _await_result(policy.on_response, pipeline_request, pipeline_response) + + with concurrent.futures.ThreadPoolExecutor() as executor: + # List comprehension to raise exceptions if happened + [ # pylint: disable=expression-not-assigned, unnecessary-comprehension + _ for _ in executor.map(parse_responses, responses) + ] + + return responses + + +def _format_data_helper(data: "FileType") -> Union[Tuple[Optional[str], str], Tuple[Optional[str], "FileContent", str]]: + """Helper for _format_data. + + Format field data according to whether it is a stream or + a string for a form-data request. + + :param data: The request field data. + :type data: str or file-like object. + :rtype: tuple[str, IO, str] or tuple[None, str] + :return: A tuple of (data name, data IO, "application/octet-stream") or (None, data str) + """ + content_type: Optional[str] = None + filename: Optional[str] = None + if isinstance(data, tuple): + if len(data) == 2: + # Filename and file bytes are included + filename, file_bytes = cast(Tuple[Optional[str], "FileContent"], data) + elif len(data) == 3: + # Filename, file object, and content_type are included + filename, file_bytes, content_type = cast(Tuple[Optional[str], "FileContent", str], data) + else: + raise ValueError( + "Unexpected data format. Expected file, or tuple of (filename, file_bytes) or " + "(filename, file_bytes, content_type)." + ) + else: + # here we just get the file content + if hasattr(data, "read"): + data = cast(IO, data) + try: + if data.name[0] != "<" and data.name[-1] != ">": + filename = os.path.basename(data.name) + except (AttributeError, TypeError): + pass + content_type = "application/octet-stream" + file_bytes = data + if content_type: + return (filename, file_bytes, content_type) + return (filename, cast(str, file_bytes)) + + +def _aiohttp_body_helper( + response: "PipelineTransportAioHttpTransportResponse", +) -> bytes: + # pylint: disable=protected-access + """Helper for body method of Aiohttp responses. + + Since aiohttp body methods need decompression work synchronously, + need to share this code across old and new aiohttp transport responses + for backcompat. + + :param response: The response to decode + :type response: ~azure.core.pipeline.transport.AioHttpTransportResponse + :rtype: bytes + :return: The response's bytes + """ + if response._content is None: + raise ValueError("Body is not available. Call async method load_body, or do your call with stream=False.") + if not response._decompress: + return response._content + if response._decompressed_content: + return response._content + enc = response.headers.get("Content-Encoding") + if not enc: + return response._content + enc = enc.lower() + if enc in ("gzip", "deflate"): + import zlib + + zlib_mode = (16 + zlib.MAX_WBITS) if enc == "gzip" else -zlib.MAX_WBITS + decompressor = zlib.decompressobj(wbits=zlib_mode) + response._content = decompressor.decompress(response._content) + response._decompressed_content = True + return response._content + return response._content + + +def get_file_items(files: "FilesType") -> Sequence[Tuple[str, "FileType"]]: + if isinstance(files, Mapping): + # casting because ItemsView technically isn't a Sequence, even + # though realistically it is ordered python 3.7 and after + return cast(Sequence[Tuple[str, "FileType"]], files.items()) + return files diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_pipeline_transport_rest_shared_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_pipeline_transport_rest_shared_async.py new file mode 100644 index 0000000000000000000000000000000000000000..d88b8dffb57be98df12099c4d51cf4df4c90eb4a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_pipeline_transport_rest_shared_async.py @@ -0,0 +1,62 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import asyncio +from typing import TYPE_CHECKING, List, Generic, TypeVar, Type, Optional, AsyncIterator, Iterator +from ..pipeline import PipelineContext, PipelineRequest, PipelineResponse +from ..pipeline._tools_async import await_result as _await_result + +if TYPE_CHECKING: + from ..pipeline.policies import SansIOHTTPPolicy + + +HttpResponseType = TypeVar("HttpResponseType") + + +class _PartGenerator(AsyncIterator[HttpResponseType], Generic[HttpResponseType]): + """Until parts is a real async iterator, wrap the sync call. + + :param response: The response to parse + :type response: ~azure.core.pipeline.transport.AsyncHttpResponse + :param default_http_response_type: The default HTTP response type to use + :type default_http_response_type: any + """ + + def __init__(self, response, default_http_response_type: Type[HttpResponseType]) -> None: + self._response = response + self._parts: Optional[Iterator[HttpResponseType]] = None + self._default_http_response_type = default_http_response_type + + async def _parse_response(self) -> Iterator[HttpResponseType]: + responses = self._response._get_raw_parts( # pylint: disable=protected-access + http_response_type=self._default_http_response_type + ) + if self._response.request.multipart_mixed_info: + policies: List["SansIOHTTPPolicy"] = self._response.request.multipart_mixed_info[1] + + async def parse_responses(response): + http_request = response.request + context = PipelineContext(None) + pipeline_request = PipelineRequest(http_request, context) + pipeline_response = PipelineResponse(http_request, response, context=context) + + for policy in policies: + await _await_result(policy.on_response, pipeline_request, pipeline_response) + + # Not happy to make this code asyncio specific, but that's multipart only for now + # If we need trio and multipart, let's reinvesitgate that later + await asyncio.gather(*[parse_responses(res) for res in responses]) + + return responses + + async def __anext__(self) -> HttpResponseType: + if not self._parts: + self._parts = iter(await self._parse_response()) + + try: + return next(self._parts) + except StopIteration: + raise StopAsyncIteration() # pylint: disable=raise-missing-from diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_utils.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c9d09a38760ebeba26a4e88c29049f885ece5b9f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/utils/_utils.py @@ -0,0 +1,188 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import datetime +import sys +from typing import ( + Any, + AsyncContextManager, + Iterable, + Iterator, + Mapping, + MutableMapping, + Optional, + Tuple, + Union, + Dict, +) +from datetime import timezone + +TZ_UTC = timezone.utc + + +class _FixedOffset(datetime.tzinfo): + """Fixed offset in minutes east from UTC. + + Copy/pasted from Python doc + + :param int offset: offset in minutes + """ + + def __init__(self, offset): + self.__offset = datetime.timedelta(minutes=offset) + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + +def _convert_to_isoformat(date_time): + """Deserialize a date in RFC 3339 format to datetime object. + Check https://tools.ietf.org/html/rfc3339#section-5.8 for examples. + + :param str date_time: The date in RFC 3339 format. + """ + if not date_time: + return None + if date_time[-1] == "Z": + delta = 0 + timestamp = date_time[:-1] + else: + timestamp = date_time[:-6] + sign, offset = date_time[-6], date_time[-5:] + delta = int(sign + offset[:1]) * 60 + int(sign + offset[-2:]) + + check_decimal = timestamp.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + timestamp = timestamp.replace(decimal_str, decimal_str[0:6]) + + if delta == 0: + tzinfo = TZ_UTC + else: + tzinfo = timezone(datetime.timedelta(minutes=delta)) + + try: + deserialized = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f") + except ValueError: + deserialized = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S") + + deserialized = deserialized.replace(tzinfo=tzinfo) + return deserialized + + +def case_insensitive_dict( + *args: Optional[Union[Mapping[str, Any], Iterable[Tuple[str, Any]]]], **kwargs: Any +) -> MutableMapping[str, Any]: + """Return a case-insensitive mutable mapping from an inputted mapping structure. + + :param args: The positional arguments to pass to the dict. + :type args: Mapping[str, Any] or Iterable[Tuple[str, Any] + :return: A case-insensitive mutable mapping object. + :rtype: ~collections.abc.MutableMapping + """ + return CaseInsensitiveDict(*args, **kwargs) + + +class CaseInsensitiveDict(MutableMapping[str, Any]): + """ + NOTE: This implementation is heavily inspired from the case insensitive dictionary from the requests library. + Thank you !! + Case insensitive dictionary implementation. + The keys are expected to be strings and will be stored in lower case. + case_insensitive_dict = CaseInsensitiveDict() + case_insensitive_dict['Key'] = 'some_value' + case_insensitive_dict['key'] == 'some_value' #True + + :param data: Initial data to store in the dictionary. + :type data: Mapping[str, Any] or Iterable[Tuple[str, Any]] + """ + + def __init__( + self, data: Optional[Union[Mapping[str, Any], Iterable[Tuple[str, Any]]]] = None, **kwargs: Any + ) -> None: + self._store: Dict[str, Any] = {} + if data is None: + data = {} + + self.update(data, **kwargs) + + def copy(self) -> "CaseInsensitiveDict": + return CaseInsensitiveDict(self._store.values()) + + def __setitem__(self, key: str, value: Any) -> None: + """Set the `key` to `value`. + + The original key will be stored with the value + + :param str key: The key to set. + :param value: The value to set the key to. + :type value: any + """ + self._store[key.lower()] = (key, value) + + def __getitem__(self, key: str) -> Any: + return self._store[key.lower()][1] + + def __delitem__(self, key: str) -> None: + del self._store[key.lower()] + + def __iter__(self) -> Iterator[str]: + return (key for key, _ in self._store.values()) + + def __len__(self) -> int: + return len(self._store) + + def lowerkey_items(self) -> Iterator[Tuple[str, Any]]: + return ((lower_case_key, pair[1]) for lower_case_key, pair in self._store.items()) + + def __eq__(self, other: Any) -> bool: + if isinstance(other, Mapping): + other = CaseInsensitiveDict(other) + else: + return False + + return dict(self.lowerkey_items()) == dict(other.lowerkey_items()) + + def __repr__(self) -> str: + return str(dict(self.items())) + + +def get_running_async_lock() -> AsyncContextManager: + """Get a lock instance from the async library that the current context is running under. + + :return: An instance of the running async library's Lock class. + :rtype: AsyncContextManager + :raises: RuntimeError if the current context is not running under an async library. + """ + + try: + import asyncio + + # Check if we are running in an asyncio event loop. + asyncio.get_running_loop() + return asyncio.Lock() + except RuntimeError as err: + # Otherwise, assume we are running in a trio event loop if it has already been imported. + if "trio" in sys.modules: + import trio # pylint: disable=networking-import-outside-azure-core-transport + + return trio.Lock() + raise RuntimeError("An asyncio or trio event loop is required.") from err diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4b9ed2562c468a7d62d3c4cc4eb41cd3a1563b0c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/__init__.py @@ -0,0 +1,45 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from .authorization_code import AuthorizationCodeCredential +from .azure_powershell import AzurePowerShellCredential +from .browser import InteractiveBrowserCredential +from .certificate import CertificateCredential +from .chained import ChainedTokenCredential +from .client_secret import ClientSecretCredential +from .default import DefaultAzureCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from .on_behalf_of import OnBehalfOfCredential +from .shared_cache import SharedTokenCacheCredential +from .azd_cli import AzureDeveloperCliCredential +from .azure_cli import AzureCliCredential +from .device_code import DeviceCodeCredential +from .user_password import UsernamePasswordCredential +from .vscode import VisualStudioCodeCredential +from .client_assertion import ClientAssertionCredential +from .workload_identity import WorkloadIdentityCredential + + +__all__ = [ + "AuthorizationCodeCredential", + "AzureCliCredential", + "AzureDeveloperCliCredential", + "AzurePowerShellCredential", + "CertificateCredential", + "ChainedTokenCredential", + "ClientAssertionCredential", + "ClientSecretCredential", + "DefaultAzureCredential", + "DeviceCodeCredential", + "EnvironmentCredential", + "InteractiveBrowserCredential", + "ManagedIdentityCredential", + "OnBehalfOfCredential", + "SharedTokenCacheCredential", + "AzureCliCredential", + "UsernamePasswordCredential", + "WorkloadIdentityCredential", + "VisualStudioCodeCredential", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/app_service.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/app_service.py new file mode 100644 index 0000000000000000000000000000000000000000..6c1a4d80ec9761d2f2a382be285b609f18481716 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/app_service.py @@ -0,0 +1,47 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Optional, Dict, Any + +from azure.core.pipeline.transport import HttpRequest + +from .._constants import EnvironmentVariables +from .._internal.managed_identity_base import ManagedIdentityBase +from .._internal.managed_identity_client import ManagedIdentityClient + + +class AppServiceCredential(ManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[ManagedIdentityClient]: + client_args = _get_client_args(**kwargs) + if client_args: + return ManagedIdentityClient(**client_args) + return None + + def get_unavailable_message(self) -> str: + return "App Service managed identity configuration not found in environment" + + +def _get_client_args(**kwargs: Any) -> Optional[Dict]: + identity_config = kwargs.pop("identity_config", None) or {} + + url = os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT) + secret = os.environ.get(EnvironmentVariables.IDENTITY_HEADER) + if not (url and secret): + # App Service managed identity isn't available in this environment + return None + + return dict( + kwargs, + identity_config=identity_config, + base_headers={"X-IDENTITY-HEADER": secret}, + request_factory=functools.partial(_get_request, url), + ) + + +def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: + request = HttpRequest("GET", url) + request.format_parameters(dict({"api-version": "2019-08-01", "resource": scope}, **identity_config)) + return request diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/application.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/application.py new file mode 100644 index 0000000000000000000000000000000000000000..bd30064d69413fd9dcc67cdc98fe1f13c1e5cb4c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/application.py @@ -0,0 +1,92 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import Any, Optional + +from azure.core.credentials import AccessToken +from .chained import ChainedTokenCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from .._constants import EnvironmentVariables +from .._internal import get_default_authority, normalize_authority + +_LOGGER = logging.getLogger(__name__) + + +class AzureApplicationCredential(ChainedTokenCredential): + """A credential for Microsoft Entra applications. + + This credential is designed for applications deployed to Azure (:class:`~azure.identity.DefaultAzureCredential` is + better suited to local development). It authenticates service principals and managed identities. + + For service principal authentication, set these environment variables to identify a principal: + + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its "directory" ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + + And one of these to authenticate that principal: + + - **AZURE_CLIENT_SECRET**: one of the service principal's client secrets + + **or** + + - **AZURE_CLIENT_CERTIFICATE_PATH**: path to a PEM-encoded certificate file including the private key. The + certificate must not be password-protected. + + See `Azure CLI documentation `_ + for more information about creating and managing service principals. + + When this environment configuration is incomplete, the credential will attempt to authenticate a managed identity. + See `Microsoft Entra ID documentation + `_ for an overview + of managed identities. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud, which is the default when no value is given for this keyword argument or + environment variable AZURE_AUTHORITY_HOST. :class:`~azure.identity.AzureAuthorityHosts` defines authorities for + other clouds. Authority configuration applies only to service principal authentication. + :keyword str managed_identity_client_id: The client ID of a user-assigned managed identity. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, a system-assigned identity will be used. + """ + + def __init__(self, **kwargs: Any) -> None: + authority = kwargs.pop("authority", None) + authority = normalize_authority(authority) if authority else get_default_authority() + managed_identity_client_id = kwargs.pop( + "managed_identity_client_id", os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + ) + super(AzureApplicationCredential, self).__init__( + EnvironmentCredential(authority=authority, **kwargs), + ManagedIdentityCredential(client_id=managed_identity_client_id, **kwargs), + ) + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + token = self._successful_credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + _LOGGER.info( + "%s acquired a token from %s", self.__class__.__name__, self._successful_credential.__class__.__name__ + ) + return token + + return super(AzureApplicationCredential, self).get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/authorization_code.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/authorization_code.py new file mode 100644 index 0000000000000000000000000000000000000000..ba47d03c2f2da1228ef30dc5a3693449e9a718f5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/authorization_code.py @@ -0,0 +1,114 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any + +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError +from .._internal.aad_client import AadClient +from .._internal.get_token_mixin import GetTokenMixin + + +class AuthorizationCodeCredential(GetTokenMixin): + """Authenticates by redeeming an authorization code previously obtained from Microsoft Entra ID. + + See `Microsoft Entra ID documentation + `_ for more information + about the authentication flow. + + :param str tenant_id: ID of the application's Microsoft Entra tenant. Also called its "directory" ID. + :param str client_id: The application's client ID + :param str authorization_code: The authorization code from the user's log-in + :param str redirect_uri: The application's redirect URI. Must match the URI used to request the authorization code. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str client_secret: One of the application's client secrets. Required only for web apps and web APIs. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_authorization_code_credential] + :end-before: [END create_authorization_code_credential] + :language: python + :dedent: 4 + :caption: Create an AuthorizationCodeCredential. + """ + + def __init__( + self, tenant_id: str, client_id: str, authorization_code: str, redirect_uri: str, **kwargs: Any + ) -> None: + self._authorization_code: Optional[str] = authorization_code + self._client_id = client_id + self._client_secret = kwargs.pop("client_secret", None) + self._client = kwargs.pop("client", None) or AadClient(tenant_id, client_id, **kwargs) + self._redirect_uri = redirect_uri + super(AuthorizationCodeCredential, self).__init__() + + def __enter__(self): + self._client.__enter__() + return self + + def __exit__(self, *args): + self._client.__exit__(*args) + + def close(self) -> None: + """Close the credential's transport session.""" + self.__exit__() + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + The first time this method is called, the credential will redeem its authorization code. On subsequent calls + the credential will return a cached access token or redeem a refresh token, if it acquired a refresh token upon + redeeming the authorization code. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. Any error response from Microsoft Entra ID is available as the error's + ``response`` attribute. + """ + # pylint:disable=useless-super-delegation + return super(AuthorizationCodeCredential, self).get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + def _acquire_token_silently(self, *scopes: str, **kwargs) -> Optional[AccessToken]: + return self._client.get_cached_access_token(scopes, **kwargs) + + def _request_token(self, *scopes: str, **kwargs) -> AccessToken: + if self._authorization_code: + token = self._client.obtain_token_by_authorization_code( + scopes=scopes, code=self._authorization_code, redirect_uri=self._redirect_uri, **kwargs + ) + self._authorization_code = None # auth codes are single-use + return token + + token = None + for refresh_token in self._client.get_cached_refresh_tokens(scopes): + if "secret" in refresh_token: + token = self._client.obtain_token_by_refresh_token(scopes, refresh_token["secret"], **kwargs) + if token: + break + + if not token: + raise ClientAuthenticationError( + message="No authorization code, cached access token, or refresh token available." + ) + + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azd_cli.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azd_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..1df2a95f208c43e57d038531b0c36a639911a44f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azd_cli.py @@ -0,0 +1,251 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +from datetime import datetime +import json +import os +import re +import shutil +import subprocess +import sys +from typing import Any, Dict, List, Optional + +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError + +from .. import CredentialUnavailableError +from .._internal import resolve_tenant, within_dac, validate_tenant_id, validate_scope +from .._internal.decorators import log_get_token + +CLI_NOT_FOUND = ( + "Azure Developer CLI could not be found. " + "Please visit https://aka.ms/azure-dev for installation instructions and then," + "once installed, authenticate to your Azure account using 'azd auth login'." +) +COMMAND_LINE = "azd auth token --output json --scope {}" +EXECUTABLE_NAME = "azd" +NOT_LOGGED_IN = "Please run 'azd auth login' from a command prompt to authenticate before using this credential." + + +class AzureDeveloperCliCredential: + """Authenticates by requesting a token from the Azure Developer CLI. + + Azure Developer CLI is a command-line interface tool that allows developers to create, manage, and deploy + resources in Azure. It's built on top of the Azure CLI and provides additional functionality specific + to Azure developers. It allows users to authenticate as a user and/or a service principal against + `Microsoft Entra ID <"https://learn.microsoft.com/azure/active-directory/fundamentals/">`__. + The AzureDeveloperCliCredential authenticates in a development environment and acquires a token on behalf of + the logged-in user or service principal in Azure Developer CLI. It acts as the Azure Developer CLI logged-in user + or service principal and executes an Azure CLI command underneath to authenticate the application against + Microsoft Entra ID. + + To use this credential, the developer needs to authenticate locally in Azure Developer CLI using one of the + commands below: + + * Run "azd auth login" in Azure Developer CLI to authenticate interactively as a user. + * Run "azd auth login --client-id 'client_id' --client-secret 'client_secret' --tenant-id 'tenant_id'" + to authenticate as a service principal. + + You may need to repeat this process after a certain time period, depending on the refresh token validity in your + organization. Generally, the refresh token validity period is a few weeks to a few months. + AzureDeveloperCliCredential will prompt you to sign in again. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure Developer CLI process to respond. Defaults + to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START azure_developer_cli_credential] + :end-before: [END azure_developer_cli_credential] + :language: python + :dedent: 4 + :caption: Create an AzureDeveloperCliCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + self.tenant_id = tenant_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + def __enter__(self) -> "AzureDeveloperCliCredential": + return self + + def __exit__(self, *args: Any) -> None: + pass + + def close(self) -> None: + """Calling this method is unnecessary.""" + + @log_get_token("AzureDeveloperCliCredential") + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke + the Azure Developer CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked + the Azure Developer CLI but didn't receive an access token. + """ + + if not scopes: + raise ValueError("Missing scope in request. \n") + + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + commandString = " --scope ".join(scopes) + command = COMMAND_LINE.format(commandString) + tenant = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + if tenant: + command += " --tenant-id " + tenant + output = _run_command(command, self._process_timeout) + + token = parse_token(output) + if not token: + sanitized_output = sanitize_output(output) + message = ( + f"Unexpected output from Azure Developer CLI: '{sanitized_output}'. \n" + f"To mitigate this issue, please refer to the troubleshooting guidelines here at " + f"https://aka.ms/azsdk/python/identity/azdevclicredential/troubleshoot." + ) + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) + + return token + + +def parse_token(output: str) -> Optional[AccessToken]: + """Parse to an AccessToken. + + In particular, convert the "expiresOn" value to epoch seconds. This value is a naive local datetime as returned by + datetime.fromtimestamp. + + :param str output: The output of the Azure Developer CLI command. + :return: An AccessToken or None if the output isn't valid. + :rtype: azure.core.credentials.AccessToken or None + """ + try: + token = json.loads(output) + dt = datetime.strptime(token["expiresOn"], "%Y-%m-%dT%H:%M:%SZ") + expires_on = dt.timestamp() + + return AccessToken(token["token"], int(expires_on)) + except (KeyError, ValueError): + return None + + +def get_safe_working_dir() -> str: + """Invoke 'azd' from a directory controlled by the OS, not the executing program's directory. + + :return: The path to the directory. + :rtype: str + :raises ~azure.identity.CredentialUnavailableError: the SYSTEMROOT environment variable is not set. + """ + + if sys.platform.startswith("win"): + path = os.environ.get("SYSTEMROOT") + if not path: + raise CredentialUnavailableError( + message="Azure Developer CLI credential" + " expects a 'SystemRoot' environment variable" + ) + return path + + return "/bin" + + +def sanitize_output(output: str) -> str: + """Redact tokens from CLI output to prevent error messages revealing them. + + :param str output: The output of the Azure Developer CLI command. + :return: The output with tokens redacted. + :rtype: str + """ + return re.sub(r"\"token\": \"(.*?)(\"|$)", "****", output) + + +def _run_command(command: str, timeout: int) -> str: + # Ensure executable exists in PATH first. This avoids a subprocess call that would fail anyway. + if shutil.which(EXECUTABLE_NAME) is None: + raise CredentialUnavailableError(message=CLI_NOT_FOUND) + + if sys.platform.startswith("win"): + args = ["cmd", "/c", command] + else: + args = ["/bin/sh", "-c", command] + try: + working_directory = get_safe_working_dir() + + kwargs: Dict[str, Any] = { + "stderr": subprocess.PIPE, + "stdin": subprocess.DEVNULL, + "cwd": working_directory, + "universal_newlines": True, + "env": dict(os.environ, NO_COLOR="true"), + "timeout": timeout, + } + + return subprocess.check_output(args, **kwargs) + except subprocess.CalledProcessError as ex: + # non-zero return from shell + # Fallback check in case the executable is not found while executing subprocess. + if ex.returncode == 127 or ex.stderr.startswith("'azd' is not recognized"): + raise CredentialUnavailableError(message=CLI_NOT_FOUND) from ex + if "not logged in, run `azd auth login` to login" in ex.stderr and "AADSTS" not in ex.stderr: + raise CredentialUnavailableError(message=NOT_LOGGED_IN) from ex + + # return code is from the CLI -> propagate its output + if ex.stderr: + message = sanitize_output(ex.stderr) + else: + message = "Failed to invoke Azure Developer CLI" + if within_dac.get(): + raise CredentialUnavailableError(message=message) from ex + raise ClientAuthenticationError(message=message) from ex + except OSError as ex: + # failed to execute 'cmd' or '/bin/sh' + error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0])) + raise error from ex + except Exception as ex: # pylint:disable=broad-except + # could be a timeout, for example + error = CredentialUnavailableError(message="Failed to invoke the Azure Developer CLI") + raise error from ex diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_arc.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_arc.py new file mode 100644 index 0000000000000000000000000000000000000000..68034300b819bb1f3257e737f0a705a9b29a3e1b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_arc.py @@ -0,0 +1,95 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Any, Dict, Optional + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.pipeline.transport import HttpRequest +from azure.core.pipeline.policies import HTTPPolicy +from azure.core.pipeline import PipelineRequest, PipelineResponse + +from .._constants import EnvironmentVariables +from .._internal.managed_identity_base import ManagedIdentityBase +from .._internal.managed_identity_client import ManagedIdentityClient + + +class AzureArcCredential(ManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[ManagedIdentityClient]: + url = os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT) + imds = os.environ.get(EnvironmentVariables.IMDS_ENDPOINT) + if url and imds: + return ManagedIdentityClient( + _per_retry_policies=[ArcChallengeAuthPolicy()], + request_factory=functools.partial(_get_request, url), + **kwargs + ) + return None + + def __enter__(self) -> "AzureArcCredential": + if self._client: + self._client.__enter__() + return self + + def __exit__(self, *args: Any) -> None: + if self._client: + self._client.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def get_unavailable_message(self) -> str: + return "Azure Arc managed identity configuration not found in environment" + + +def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: + if identity_config: + raise ClientAuthenticationError( + message="User assigned managed identities are not supported by Azure Arc. To authenticate with the system " + "assigned identity omit the client id when constructing the credential, and if authenticating with " + "DefaultAzureCredential ensure the AZURE_CLIENT_ID environment variable is not set." + ) + + request = HttpRequest("GET", url) + request.format_parameters(dict({"api-version": "2019-11-01", "resource": scope}, **identity_config)) + return request + + +def _get_secret_key(response: PipelineResponse) -> str: + # expecting header containing path to secret key file + header = response.http_response.headers.get("WWW-Authenticate") + if not header: + raise ClientAuthenticationError(message="Did not receive a value from WWW-Authenticate header") + + # expecting header with structure like 'Basic realm=' + try: + key_file = header.split("=")[1] + except IndexError as ex: + raise ClientAuthenticationError( + message="Did not receive a correct value from WWW-Authenticate header: {}".format(header) + ) from ex + with open(key_file, "r", encoding="utf-8") as file: + try: + return file.read() + except Exception as error: # pylint:disable=broad-except + # user is expected to have obtained read permission prior to this being called + raise ClientAuthenticationError( + message="Could not read file {} contents: {}".format(key_file, error) + ) from error + + +class ArcChallengeAuthPolicy(HTTPPolicy): + """Policy for handling Azure Arc's challenge authentication""" + + def send(self, request: PipelineRequest) -> PipelineResponse: + request.http_request.headers["Metadata"] = "true" + response = self.next.send(request) + + if response.http_response.status_code == 401: + secret_key = _get_secret_key(response) + request.http_request.headers["Authorization"] = "Basic {}".format(secret_key) + response = self.next.send(request) + + return response diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_cli.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..fde3e4d9bf13d93e08687a5b12fa0578deab7678 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_cli.py @@ -0,0 +1,225 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from datetime import datetime +import json +import os +import re +import shutil +import subprocess +import sys +import time +from typing import List, Optional, Any, Dict + +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError + +from .. import CredentialUnavailableError +from .._internal import _scopes_to_resource, resolve_tenant, within_dac, validate_tenant_id, validate_scope +from .._internal.decorators import log_get_token + + +CLI_NOT_FOUND = "Azure CLI not found on path" +COMMAND_LINE = "az account get-access-token --output json --resource {}" +EXECUTABLE_NAME = "az" +NOT_LOGGED_IN = "Please run 'az login' to set up an account" + + +class AzureCliCredential: + """Authenticates by requesting a token from the Azure CLI. + + This requires previously logging in to Azure via "az login", and will use the CLI's currently logged in identity. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure CLI process to respond. Defaults to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_azure_cli_credential] + :end-before: [END create_azure_cli_credential] + :language: python + :dedent: 4 + :caption: Create an AzureCliCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + self.tenant_id = tenant_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + def close(self) -> None: + """Calling this method is unnecessary.""" + + @log_get_token("AzureCliCredential") + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke the Azure CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked the Azure CLI but didn't + receive an access token. + """ + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + resource = _scopes_to_resource(*scopes) + command = COMMAND_LINE.format(resource) + tenant = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + if tenant: + command += " --tenant " + tenant + output = _run_command(command, self._process_timeout) + + token = parse_token(output) + if not token: + sanitized_output = sanitize_output(output) + message = ( + f"Unexpected output from Azure CLI: '{sanitized_output}'. \n" + f"To mitigate this issue, please refer to the troubleshooting guidelines here at " + f"https://aka.ms/azsdk/python/identity/azclicredential/troubleshoot." + ) + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) + + return token + + +def parse_token(output) -> Optional[AccessToken]: + """Parse output of 'az account get-access-token' to an AccessToken. + + In particular, convert the "expiresOn" value to epoch seconds. This value is a naive local datetime as returned by + datetime.fromtimestamp. + + :param str output: Output of 'az' command. + :return: An AccessToken or None if the output isn't valid. + :rtype: azure.core.credentials.AccessToken or None + """ + try: + token = json.loads(output) + dt = datetime.strptime(token["expiresOn"], "%Y-%m-%d %H:%M:%S.%f") + if hasattr(dt, "timestamp"): + # Python >= 3.3 + expires_on = dt.timestamp() + else: + # taken from Python 3.5's datetime.timestamp() + expires_on = time.mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, -1, -1, -1)) + + return AccessToken(token["accessToken"], int(expires_on)) + except (KeyError, ValueError): + return None + + +def get_safe_working_dir() -> str: + """Invoke 'az' from a directory controlled by the OS, not the executing program's directory. + + :return: The path to the directory. + :rtype: str + """ + + if sys.platform.startswith("win"): + path = os.environ.get("SYSTEMROOT") + if not path: + raise CredentialUnavailableError(message="Environment variable 'SYSTEMROOT' has no value") + return path + + return "/bin" + + +def sanitize_output(output: str) -> str: + """Redact access tokens from CLI output to prevent error messages revealing them. + + :param str output: The output of the Azure CLI. + :return: The output with access tokens redacted. + :rtype: str + """ + return re.sub(r"\"accessToken\": \"(.*?)(\"|$)", "****", output) + + +def _run_command(command: str, timeout: int) -> str: + # Ensure executable exists in PATH first. This avoids a subprocess call that would fail anyway. + if shutil.which(EXECUTABLE_NAME) is None: + raise CredentialUnavailableError(message=CLI_NOT_FOUND) + + if sys.platform.startswith("win"): + args = ["cmd", "/c", command] + else: + args = ["/bin/sh", "-c", command] + try: + working_directory = get_safe_working_dir() + + kwargs: Dict[str, Any] = { + "stderr": subprocess.PIPE, + "stdin": subprocess.DEVNULL, + "cwd": working_directory, + "universal_newlines": True, + "timeout": timeout, + "env": dict(os.environ, AZURE_CORE_NO_COLOR="true"), + } + return subprocess.check_output(args, **kwargs) + except subprocess.CalledProcessError as ex: + # non-zero return from shell + # Fallback check in case the executable is not found while executing subprocess. + if ex.returncode == 127 or ex.stderr.startswith("'az' is not recognized"): + raise CredentialUnavailableError(message=CLI_NOT_FOUND) from ex + if ("az login" in ex.stderr or "az account set" in ex.stderr) and "AADSTS" not in ex.stderr: + raise CredentialUnavailableError(message=NOT_LOGGED_IN) from ex + + # return code is from the CLI -> propagate its output + if ex.stderr: + message = sanitize_output(ex.stderr) + else: + message = "Failed to invoke Azure CLI" + if within_dac.get(): + raise CredentialUnavailableError(message=message) from ex + raise ClientAuthenticationError(message=message) from ex + except OSError as ex: + # failed to execute 'cmd' or '/bin/sh' + error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0])) + raise error from ex + except Exception as ex: # pylint:disable=broad-except + # could be a timeout, for example + error = CredentialUnavailableError(message="Failed to invoke the Azure CLI") + raise error from ex diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_ml.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_ml.py new file mode 100644 index 0000000000000000000000000000000000000000..949e7d0fd2fc11328199bafa47fc0924ba6d591a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_ml.py @@ -0,0 +1,87 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Optional, Dict + +from azure.core.pipeline.transport import HttpRequest + +from .._constants import EnvironmentVariables +from .._internal.managed_identity_base import ManagedIdentityBase +from .._internal.managed_identity_client import ManagedIdentityClient + + +class AzureMLCredential(ManagedIdentityBase): + def get_client(self, **kwargs) -> Optional[ManagedIdentityClient]: + client_args = _get_client_args(**kwargs) + if client_args: + return ManagedIdentityClient(**client_args) + return None + + def get_unavailable_message(self) -> str: + return "Azure ML managed identity configuration not found in environment" + + +def _get_client_args(**kwargs) -> Optional[Dict]: + identity_config = kwargs.pop("identity_config", None) or {} + + url = os.environ.get(EnvironmentVariables.MSI_ENDPOINT) + secret = os.environ.get(EnvironmentVariables.MSI_SECRET) + if not (url and secret): + # Azure ML managed identity isn't available in this environment + return None + + if kwargs.get("client_id"): + identity_config["clientid"] = kwargs.pop("client_id") + + return dict( + kwargs, + _content_callback=_parse_expires_on, + identity_config=identity_config, + base_headers={"secret": secret}, + request_factory=functools.partial(_get_request, url), + ) + + +def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: + request = HttpRequest("GET", url) + request.format_parameters(dict({"api-version": "2017-09-01", "resource": scope}, **identity_config)) + return request + + +def _parse_expires_on(content: Dict) -> None: + """Parse an App Service MSI version 2017-09-01 expires_on value to epoch seconds. + + This version of the API returns expires_on as a UTC datetime string rather than epoch seconds. The string's + format depends on the OS. Responses on Windows include AM/PM, for example "1/16/2020 5:24:12 AM +00:00". + Responses on Linux do not, for example "06/20/2019 02:57:58 +00:00". + + :param dict content: a deserialized response from an App Service MSI. + :raises ValueError: ``expires_on`` didn't match an expected format + """ + + # Azure ML sets the same environment variables as App Service but returns expires_on as an integer. + # That means we could have an Azure ML response here, so let's first try to parse expires_on as an int. + try: + content["expires_on"] = int(content["expires_on"]) + return + except ValueError: + pass + + import calendar + import time + + expires_on = content["expires_on"] + if expires_on.endswith(" +00:00"): + date_string = expires_on[: -len(" +00:00")] + for format_string in ("%m/%d/%Y %H:%M:%S", "%m/%d/%Y %I:%M:%S %p"): # (Linux, Windows) + try: + t = time.strptime(date_string, format_string) + content["expires_on"] = calendar.timegm(t) + return + except ValueError: + pass + + raise ValueError("'{}' doesn't match the expected format".format(expires_on)) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_powershell.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_powershell.py new file mode 100644 index 0000000000000000000000000000000000000000..810d0408e94d1f315473619fa1201c93d8f4fc87 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/azure_powershell.py @@ -0,0 +1,215 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import base64 +import logging +import subprocess +import sys +from typing import Any, List, Tuple, Optional + +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError + +from .azure_cli import get_safe_working_dir +from .. import CredentialUnavailableError +from .._internal import _scopes_to_resource, resolve_tenant, within_dac, validate_tenant_id, validate_scope +from .._internal.decorators import log_get_token + + +_LOGGER = logging.getLogger(__name__) + +AZ_ACCOUNT_NOT_INSTALLED = "Az.Account module >= 2.2.0 is not installed" +BLOCKED_BY_EXECUTION_POLICY = "Execution policy prevented invoking Azure PowerShell" +NO_AZ_ACCOUNT_MODULE = "NO_AZ_ACCOUNT_MODULE" +POWERSHELL_NOT_INSTALLED = "PowerShell is not installed" +RUN_CONNECT_AZ_ACCOUNT = 'Please run "Connect-AzAccount" to set up account' +SCRIPT = """$ErrorActionPreference = 'Stop' +[version]$minimumVersion = '2.2.0' + +$m = Import-Module Az.Accounts -MinimumVersion $minimumVersion -PassThru -ErrorAction SilentlyContinue + +if (! $m) {{ + Write-Output {} + exit +}} + +$token = Get-AzAccessToken -ResourceUrl '{}'{} + +Write-Output "`nazsdk%$($token.Token)%$($token.ExpiresOn.ToUnixTimeSeconds())`n" +""" + + +class AzurePowerShellCredential: + """Authenticates by requesting a token from Azure PowerShell. + + This requires previously logging in to Azure via "Connect-AzAccount", and will use the currently logged in identity. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure PowerShell process to respond. Defaults to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_azure_power_shell_credential] + :end-before: [END create_azure_power_shell_credential] + :language: python + :dedent: 4 + :caption: Create an AzurePowerShellCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + self.tenant_id = tenant_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + def close(self) -> None: + """Calling this method is unnecessary.""" + + @log_get_token("AzurePowerShellCredential") + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke Azure PowerShell, or + no account is authenticated + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked Azure PowerShell but didn't + receive an access token + """ + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + tenant_id = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + command_line = get_command_line(scopes, tenant_id) + output = run_command_line(command_line, self._process_timeout) + token = parse_token(output) + return token + + +def run_command_line(command_line: List[str], timeout: int) -> str: + stdout = stderr = "" + proc = None + kwargs = {"timeout": timeout} + + try: + proc = start_process(command_line) + stdout, stderr = proc.communicate(**kwargs) + if sys.platform.startswith("win") and "' is not recognized" in stderr: + # pwsh.exe isn't on the path; try powershell.exe + command_line[-1] = command_line[-1].replace("pwsh", "powershell", 1) + proc = start_process(command_line) + stdout, stderr = proc.communicate(**kwargs) + + except Exception as ex: # pylint:disable=broad-except + # failed to execute "cmd" or "/bin/sh", or timed out; PowerShell and Az.Account may or may not be installed + # (handling Exception here because subprocess.SubprocessError and .TimeoutExpired were added in 3.3) + if proc and not proc.returncode: + proc.kill() + error = CredentialUnavailableError( + message="Failed to invoke PowerShell.\n" + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/powershellcredential/troubleshoot." + ) + raise error from ex + + raise_for_error(proc.returncode, stdout, stderr) + return stdout + + +def start_process(args: List[str]) -> "subprocess.Popen": + working_directory = get_safe_working_dir() + proc = subprocess.Popen( # pylint:disable=consider-using-with + args, + cwd=working_directory, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.DEVNULL, + universal_newlines=True, + ) + return proc + + +def parse_token(output: str) -> AccessToken: + for line in output.split(): + if line.startswith("azsdk%"): + _, token, expires_on = line.split("%") + return AccessToken(token, int(expires_on)) + + if within_dac.get(): + raise CredentialUnavailableError(message='Unexpected output from Get-AzAccessToken: "{}"'.format(output)) + raise ClientAuthenticationError(message='Unexpected output from Get-AzAccessToken: "{}"'.format(output)) + + +def get_command_line(scopes: Tuple[str, ...], tenant_id: str) -> List[str]: + if tenant_id: + tenant_argument = " -TenantId " + tenant_id + else: + tenant_argument = "" + resource = _scopes_to_resource(*scopes) + script = SCRIPT.format(NO_AZ_ACCOUNT_MODULE, resource, tenant_argument) + encoded_script = base64.b64encode(script.encode("utf-16-le")).decode() + + command = "pwsh -NoProfile -NonInteractive -EncodedCommand " + encoded_script + if sys.platform.startswith("win"): + return ["cmd", "/c", command] + return ["/bin/sh", "-c", command] + + +def raise_for_error(return_code: int, stdout: str, stderr: str) -> None: + if return_code == 0: + if NO_AZ_ACCOUNT_MODULE in stdout: + raise CredentialUnavailableError(AZ_ACCOUNT_NOT_INSTALLED) + return + + if return_code == 127 or "' is not recognized" in stderr: + raise CredentialUnavailableError(message=POWERSHELL_NOT_INSTALLED) + if "Run Connect-AzAccount to login" in stderr: + raise CredentialUnavailableError(message=RUN_CONNECT_AZ_ACCOUNT) + if "AuthorizationManager check failed" in stderr: + raise CredentialUnavailableError(message=BLOCKED_BY_EXECUTION_POLICY) + + if stderr: + # stderr is too noisy to include with an exception but may be useful for debugging + _LOGGER.debug('%s received an error from Azure PowerShell: "%s"', AzurePowerShellCredential.__name__, stderr) + raise CredentialUnavailableError(message="Failed to invoke PowerShell") diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/browser.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/browser.py new file mode 100644 index 0000000000000000000000000000000000000000..0f0686056670ca7effe04125099de0800ce0c54a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/browser.py @@ -0,0 +1,155 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import platform +import socket +from typing import Dict, Any +import subprocess +import webbrowser +from urllib.parse import urlparse + +from azure.core.exceptions import ClientAuthenticationError + +from .. import CredentialUnavailableError +from .._constants import DEVELOPER_SIGN_ON_CLIENT_ID +from .._internal import AuthCodeRedirectServer, InteractiveCredential, wrap_exceptions, within_dac + + +class InteractiveBrowserCredential(InteractiveCredential): + """Opens a browser to interactively authenticate a user. + + :func:`~get_token` opens a browser to a login URL provided by Microsoft Entra ID and authenticates a user + there with the authorization code flow, using PKCE (Proof Key for Code Exchange) internally to protect the code. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str tenant_id: a Microsoft Entra tenant ID. Defaults to the "organizations" tenant, which can + authenticate work or school accounts. + :keyword str client_id: Client ID of the Microsoft Entra application users will sign in to. If + unspecified, users will authenticate to an Azure development application. + :keyword str login_hint: a username suggestion to pre-fill the login page's username/email address field. A user + may still log in with a different username. + :keyword str redirect_uri: a redirect URI for the application identified by `client_id` as configured in Azure + Active Directory, for example "http://localhost:8400". This is only required when passing a value for + **client_id**, and must match a redirect URI in the application's registration. The credential must be able to + bind a socket to this URI. + :keyword AuthenticationRecord authentication_record: :class:`AuthenticationRecord` returned by :func:`authenticate` + :keyword bool disable_automatic_authentication: if True, :func:`get_token` will raise + :class:`AuthenticationRequiredError` when user interaction is required to acquire a token. Defaults to False. + :keyword cache_persistence_options: configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword int timeout: seconds to wait for the user to complete authentication. Defaults to 300 (5 minutes). + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword bool enable_support_logging: Enables additional support logging in the underlying MSAL library. + This logging potentially contains personally identifiable information and is intended to be used only for + troubleshooting purposes. + :raises ValueError: invalid **redirect_uri** + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_interactive_browser_credential] + :end-before: [END create_interactive_browser_credential] + :language: python + :dedent: 4 + :caption: Create an InteractiveBrowserCredential. + """ + + def __init__(self, **kwargs: Any) -> None: + redirect_uri = kwargs.pop("redirect_uri", None) + if redirect_uri: + self._parsed_url = urlparse(redirect_uri) + if not (self._parsed_url.hostname and self._parsed_url.port): + raise ValueError('"redirect_uri" must be a URL with port number, for example "http://localhost:8400"') + else: + self._parsed_url = None + + self._login_hint = kwargs.pop("login_hint", None) + self._timeout = kwargs.pop("timeout", 300) + self._server_class = kwargs.pop("_server_class", AuthCodeRedirectServer) + client_id = kwargs.pop("client_id", DEVELOPER_SIGN_ON_CLIENT_ID) + super(InteractiveBrowserCredential, self).__init__(client_id=client_id, **kwargs) + + @wrap_exceptions + def _request_token(self, *scopes: str, **kwargs) -> Dict: + + # start an HTTP server to receive the redirect + server = None + redirect_uri: str = "" + if self._parsed_url: + try: + redirect_uri = "http://{}:{}".format(self._parsed_url.hostname, self._parsed_url.port) + server = self._server_class(self._parsed_url.hostname, self._parsed_url.port, timeout=self._timeout) + except socket.error as ex: + raise CredentialUnavailableError(message="Couldn't start an HTTP server on " + redirect_uri) from ex + else: + for port in range(8400, 9000): + try: + server = self._server_class("localhost", port, timeout=self._timeout) + redirect_uri = "http://localhost:{}".format(port) + break + except socket.error: + continue # keep looking for an open port + + if not server: + raise CredentialUnavailableError(message="Couldn't start an HTTP server on localhost") + + # get the url the user must visit to authenticate + scopes = list(scopes) # type: ignore + claims = kwargs.get("claims") + app = self._get_app(**kwargs) + flow = app.initiate_auth_code_flow( + scopes, + redirect_uri=redirect_uri, + prompt="select_account", + claims_challenge=claims, + login_hint=self._login_hint, + ) + if "auth_uri" not in flow: + raise CredentialUnavailableError("Failed to begin authentication flow") + + if not _open_browser(flow["auth_uri"]): + raise CredentialUnavailableError(message="Failed to open a browser") + + # block until the server times out or receives the post-authentication redirect + response = server.wait_for_redirect() + if not response: + if within_dac.get(): + raise CredentialUnavailableError( + message="Timed out after waiting {} seconds for the user to authenticate".format(self._timeout) + ) + raise ClientAuthenticationError( + message="Timed out after waiting {} seconds for the user to authenticate".format(self._timeout) + ) + + # redeem the authorization code for a token + return app.acquire_token_by_auth_code_flow(flow, response, scopes=scopes, claims_challenge=claims) + + +def _open_browser(url): + opened = webbrowser.open(url) + if not opened: + uname = platform.uname() + system = uname[0].lower() + release = uname[2].lower() + if "microsoft" in release and system == "linux": + kwargs = {"timeout": 5} + + try: + exit_code = subprocess.call( + ["powershell.exe", "-NoProfile", "-Command", 'Start-Process "{}"'.format(url)], **kwargs + ) + opened = exit_code == 0 + except Exception: # pylint:disable=broad-except + # powershell.exe isn't available, or the subprocess timed out + pass + return opened diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/certificate.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/certificate.py new file mode 100644 index 0000000000000000000000000000000000000000..41533cb11b671b3f8fec772a0bb6e1690d4bd09f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/certificate.py @@ -0,0 +1,182 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from binascii import hexlify +from typing import cast, NamedTuple, Union, Dict, Any, Optional + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey +from cryptography.hazmat.backends import default_backend + +from .._internal import validate_tenant_id +from .._internal.client_credential_base import ClientCredentialBase + + +class CertificateCredential(ClientCredentialBase): + """Authenticates as a service principal using a certificate. + + The certificate must have an RSA private key, because this credential signs assertions using RS256. See + `Microsoft Entra ID documentation + `_ + for more information on configuring certificate authentication. + + :param str tenant_id: ID of the service principal's tenant. Also called its "directory" ID. + :param str client_id: The service principal's client ID + :param str certificate_path: Optional path to a certificate file in PEM or PKCS12 format, including the private + key. If not provided, **certificate_data** is required. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword bytes certificate_data: The bytes of a certificate in PEM or PKCS12 format, including the private key + :keyword password: The certificate's password. If a unicode string, it will be encoded as UTF-8. If the certificate + requires a different encoding, pass appropriately encoded bytes instead. + :paramtype password: str or bytes + :keyword bool send_certificate_chain: If True, the credential will send the public certificate chain in the x5c + header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication. Defaults to + False. + :keyword cache_persistence_options: Configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_certificate_credential] + :end-before: [END create_certificate_credential] + :language: python + :dedent: 4 + :caption: Create a CertificateCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, certificate_path: Optional[str] = None, **kwargs: Any) -> None: + validate_tenant_id(tenant_id) + + client_credential = get_client_credential(certificate_path, **kwargs) + + super(CertificateCredential, self).__init__( + client_id=client_id, client_credential=client_credential, tenant_id=tenant_id, **kwargs + ) + + +def extract_cert_chain(pem_bytes: bytes) -> bytes: + """Extract a certificate chain from a PEM file's bytes, removing line breaks. + + :param bytes pem_bytes: The PEM file's bytes + :return: The certificate chain + :rtype: bytes + """ + + # if index raises ValueError, there's no PEM-encoded cert + start = pem_bytes.index(b"-----BEGIN CERTIFICATE-----") + footer = b"-----END CERTIFICATE-----" + end = pem_bytes.rindex(footer) + chain = pem_bytes[start : end + len(footer) + 1] + + return b"".join(chain.splitlines()) + + +_Cert = NamedTuple("_Cert", [("pem_bytes", bytes), ("private_key", "Any"), ("fingerprint", bytes)]) + + +def load_pem_certificate(certificate_data: bytes, password: Optional[bytes] = None) -> _Cert: + private_key = serialization.load_pem_private_key(certificate_data, password, backend=default_backend()) + cert = x509.load_pem_x509_certificate(certificate_data, default_backend()) + fingerprint = cert.fingerprint(hashes.SHA1()) # nosec + return _Cert(certificate_data, private_key, fingerprint) + + +def load_pkcs12_certificate(certificate_data: bytes, password: Optional[bytes] = None) -> _Cert: + from cryptography.hazmat.primitives.serialization import Encoding, NoEncryption, pkcs12, PrivateFormat + + try: + private_key, cert, additional_certs = pkcs12.load_key_and_certificates( + certificate_data, password, backend=default_backend() + ) + except ValueError as ex: + # mentioning PEM here because we raise this error when certificate_data is garbage + raise ValueError("Failed to deserialize certificate in PEM or PKCS12 format") from ex + if not private_key: + raise ValueError("The certificate must include its private key") + if not cert: + raise ValueError("Failed to deserialize certificate in PEM or PKCS12 format") + + # This serializes the private key without any encryption it may have had. Doing so doesn't violate security + # boundaries because this representation of the key is kept in memory. We already have the key and its + # password, if any, in memory. + key_bytes = private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) + pem_sections = [key_bytes] + [c.public_bytes(Encoding.PEM) for c in [cert] + additional_certs] + pem_bytes = b"".join(pem_sections) + + fingerprint = cert.fingerprint(hashes.SHA1()) # nosec + + return _Cert(pem_bytes, private_key, fingerprint) + + +def get_client_credential( + certificate_path: Optional[str] = None, + password: Optional[Union[bytes, str]] = None, + certificate_data: Optional[bytes] = None, + send_certificate_chain: bool = False, + **_: Any +) -> Dict: + """Load a certificate from a filesystem path or bytes, return it as a dict suitable for msal.ClientApplication. + + :param str certificate_path: Path to a PEM or PKCS12 certificate file. + :param bytes password: The certificate's password, if any. + :param bytes certificate_data: The PEM or PKCS12 certificate's bytes. + :param bool send_certificate_chain: Whether to send the certificate chain. Defaults to False. + + :return: The certificate as a dict + :rtype: dict + """ + + if certificate_path: + if certificate_data: + raise ValueError('Please specify either "certificate_path" or "certificate_data", not both') + with open(certificate_path, "rb") as f: + certificate_data = f.read() + elif not certificate_data: + raise ValueError('CertificateCredential requires a value for either "certificate_path" or "certificate_data"') + + if password: + # if password is already bytes, no need to encode. + if isinstance(password, str): + password = password.encode("utf-8") + password = cast("Optional[bytes]", password) + + if b"-----BEGIN" in certificate_data: + cert = load_pem_certificate(certificate_data, password) + else: + cert = load_pkcs12_certificate(certificate_data, password) + password = None # load_pkcs12_certificate returns cert.pem_bytes decrypted + + if not isinstance(cert.private_key, RSAPrivateKey): + raise ValueError("The certificate must have an RSA private key because RS256 is used for signing") + + client_credential = {"private_key": cert.pem_bytes, "thumbprint": hexlify(cert.fingerprint).decode("utf-8")} + if password: + client_credential["passphrase"] = password + + if send_certificate_chain: + try: + # the JWT needs the whole chain but load_pem_x509_certificate deserializes only the signing cert + chain = extract_cert_chain(cert.pem_bytes) + client_credential["public_certificate"] = chain.decode("utf-8") + except ValueError as ex: + # we shouldn't land here--cryptography already loaded the cert and would have raised if it were malformed + raise ValueError("Malformed certificate") from ex + + return client_credential diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/chained.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/chained.py new file mode 100644 index 0000000000000000000000000000000000000000..f55cc7ff139cbf25a5c4a039f406430bc8becde1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/chained.py @@ -0,0 +1,124 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +from typing import Any, Optional, TYPE_CHECKING +from azure.core.exceptions import ClientAuthenticationError + +from azure.core.credentials import AccessToken +from .. import CredentialUnavailableError +from .._internal import within_credential_chain + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + +_LOGGER = logging.getLogger(__name__) + + +def _get_error_message(history): + attempts = [] + for credential, error in history: + if error: + attempts.append("{}: {}".format(credential.__class__.__name__, error)) + else: + attempts.append(credential.__class__.__name__) + return """ +Attempted credentials:\n\t{}""".format( + "\n\t".join(attempts) + ) + + +class ChainedTokenCredential: + """A sequence of credentials that is itself a credential. + + Its :func:`get_token` method calls ``get_token`` on each credential in the sequence, in order, returning the first + valid token received. + + :param credentials: credential instances to form the chain + :type credentials: ~azure.core.credentials.TokenCredential + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_chained_token_credential] + :end-before: [END create_chained_token_credential] + :language: python + :dedent: 4 + :caption: Create a ChainedTokenCredential. + """ + + def __init__(self, *credentials): + # type: (*TokenCredential) -> None + if not credentials: + raise ValueError("at least one credential is required") + + self._successful_credential = None # type: Optional[TokenCredential] + self.credentials = credentials + + def __enter__(self): + for credential in self.credentials: + credential.__enter__() # type: ignore + return self + + def __exit__(self, *args: Any): + for credential in self.credentials: + credential.__exit__(*args) # type: ignore + + def close(self) -> None: + """Close the transport session of each credential in the chain.""" + self.__exit__() + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request a token from each chained credential, in order, returning the first token received. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: no credential in the chain provided a token + """ + within_credential_chain.set(True) + history = [] + for credential in self.credentials: + try: + token = credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + _LOGGER.info("%s acquired a token from %s", self.__class__.__name__, credential.__class__.__name__) + self._successful_credential = credential + within_credential_chain.set(False) + return token + except CredentialUnavailableError as ex: + # credential didn't attempt authentication because it lacks required data or state -> continue + history.append((credential, ex.message)) + except Exception as ex: # pylint: disable=broad-except + # credential failed to authenticate, or something unexpectedly raised -> break + history.append((credential, str(ex))) + _LOGGER.debug( + '%s.get_token failed: %s raised unexpected error "%s"', + self.__class__.__name__, + credential.__class__.__name__, + ex, + exc_info=True, + ) + break + + within_credential_chain.set(False) + attempts = _get_error_message(history) + message = ( + self.__class__.__name__ + + " failed to retrieve a token from the included credentials." + + attempts + + "\nTo mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/defaultazurecredential/troubleshoot." + ) + _LOGGER.warning(message) + raise ClientAuthenticationError(message=message) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/client_assertion.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/client_assertion.py new file mode 100644 index 0000000000000000000000000000000000000000..0511816e10ea5ff11555e8e2f02536abee97719b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/client_assertion.py @@ -0,0 +1,62 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Callable, Optional, Any + +from azure.core.credentials import AccessToken +from .._internal import AadClient +from .._internal.get_token_mixin import GetTokenMixin + + +class ClientAssertionCredential(GetTokenMixin): + """Authenticates a service principal with a JWT assertion. + + This credential is for advanced scenarios. :class:`~azure.identity.CertificateCredential` has a more + convenient API for the most common assertion scenario, authenticating a service principal with a certificate. + + :param str tenant_id: ID of the principal's tenant. Also called its "directory" ID. + :param str client_id: The principal's client ID + :param func: A callable that returns a string assertion. The credential will call this every time it + acquires a new token. + :paramtype func: Callable[[], str] + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud (which is the default). + :class:`~azure.identity.AzureAuthorityHosts` defines authorities for other clouds. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_client_assertion_credential] + :end-before: [END create_client_assertion_credential] + :language: python + :dedent: 4 + :caption: Create a ClientAssertionCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, func: Callable[[], str], **kwargs: Any) -> None: + self._func = func + self._client = AadClient(tenant_id, client_id, **kwargs) + super(ClientAssertionCredential, self).__init__(**kwargs) + + def __enter__(self): + self._client.__enter__() + return self + + def __exit__(self, *args): + self._client.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + return self._client.get_cached_access_token(scopes, **kwargs) + + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + assertion = self._func() + token = self._client.obtain_token_by_jwt_assertion(scopes, assertion, **kwargs) + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/client_secret.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/client_secret.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac73a74415a68ede2fb2ad0b9fa862b39512e4a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/client_secret.py @@ -0,0 +1,53 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any +from .._internal.client_credential_base import ClientCredentialBase + + +class ClientSecretCredential(ClientCredentialBase): + """Authenticates as a service principal using a client secret. + + :param str tenant_id: ID of the service principal's tenant. Also called its "directory" ID. + :param str client_id: The service principal's client ID + :param str client_secret: One of the service principal's client secrets + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword cache_persistence_options: Configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_client_secret_credential] + :end-before: [END create_client_secret_credential] + :language: python + :dedent: 4 + :caption: Create a ClientSecretCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, client_secret: str, **kwargs: Any) -> None: + if not client_id: + raise ValueError("client_id should be the id of a Microsoft Entra application") + if not client_secret: + raise ValueError("secret should be a Microsoft Entra application's client secret") + if not tenant_id: + raise ValueError("tenant_id should be a Microsoft Entra tenant's id (also called its 'directory id')") + + super(ClientSecretCredential, self).__init__( + client_id=client_id, client_credential=client_secret, tenant_id=tenant_id, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/cloud_shell.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/cloud_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..ab3a337bdc62625d11d94aaa803fb04cdbf62342 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/cloud_shell.py @@ -0,0 +1,31 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Any, Optional, Dict + +from azure.core.pipeline.transport import HttpRequest + +from .._constants import EnvironmentVariables +from .._internal.managed_identity_client import ManagedIdentityClient +from .._internal.managed_identity_base import ManagedIdentityBase + + +class CloudShellCredential(ManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[ManagedIdentityClient]: + url = os.environ.get(EnvironmentVariables.MSI_ENDPOINT) + if url: + return ManagedIdentityClient( + request_factory=functools.partial(_get_request, url), base_headers={"Metadata": "true"}, **kwargs + ) + return None + + def get_unavailable_message(self) -> str: + return "Cloud Shell managed identity configuration not found in environment" + + +def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: + request = HttpRequest("POST", url, data=dict({"resource": scope}, **identity_config)) + return request diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/default.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/default.py new file mode 100644 index 0000000000000000000000000000000000000000..b5e039be04a8781d9b50dd5fca32809dfbb13712 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/default.py @@ -0,0 +1,227 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import List, TYPE_CHECKING, Any, Optional, cast + +from azure.core.credentials import AccessToken +from .._constants import EnvironmentVariables +from .._internal import get_default_authority, normalize_authority, within_dac +from .azure_powershell import AzurePowerShellCredential +from .browser import InteractiveBrowserCredential +from .chained import ChainedTokenCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from .shared_cache import SharedTokenCacheCredential +from .azure_cli import AzureCliCredential +from .azd_cli import AzureDeveloperCliCredential +from .vscode import VisualStudioCodeCredential +from .workload_identity import WorkloadIdentityCredential + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + +_LOGGER = logging.getLogger(__name__) + + +class DefaultAzureCredential(ChainedTokenCredential): + """A default credential capable of handling most Azure SDK authentication scenarios. + + The identity it uses depends on the environment. When an access token is needed, it requests one using these + identities in turn, stopping when one provides a token: + + 1. A service principal configured by environment variables. See :class:`~azure.identity.EnvironmentCredential` for + more details. + 2. WorkloadIdentityCredential if environment variable configuration is set by the Azure workload + identity webhook. + 3. An Azure managed identity. See :class:`~azure.identity.ManagedIdentityCredential` for more details. + 4. On Windows only: a user who has signed in with a Microsoft application, such as Visual Studio. If multiple + identities are in the cache, then the value of the environment variable ``AZURE_USERNAME`` is used to select + which identity to use. See :class:`~azure.identity.SharedTokenCacheCredential` for more details. + 5. The identity currently logged in to the Azure CLI. + 6. The identity currently logged in to Azure PowerShell. + 7. The identity currently logged in to the Azure Developer CLI. + + This default behavior is configurable with keyword arguments. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. Managed identities ignore this because they reside in a single cloud. + :keyword bool exclude_workload_identity_credential: Whether to exclude the workload identity from the credential. + Defaults to **False**. + :keyword bool exclude_developer_cli_credential: Whether to exclude the Azure Developer CLI + from the credential. Defaults to **False**. + :keyword bool exclude_cli_credential: Whether to exclude the Azure CLI from the credential. Defaults to **False**. + :keyword bool exclude_environment_credential: Whether to exclude a service principal configured by environment + variables from the credential. Defaults to **False**. + :keyword bool exclude_managed_identity_credential: Whether to exclude managed identity from the credential. + Defaults to **False**. + :keyword bool exclude_powershell_credential: Whether to exclude Azure PowerShell. Defaults to **False**. + :keyword bool exclude_visual_studio_code_credential: Whether to exclude stored credential from VS Code. + Defaults to **True**. + :keyword bool exclude_shared_token_cache_credential: Whether to exclude the shared token cache. Defaults to + **False**. + :keyword bool exclude_interactive_browser_credential: Whether to exclude interactive browser authentication (see + :class:`~azure.identity.InteractiveBrowserCredential`). Defaults to **True**. + :keyword str interactive_browser_tenant_id: Tenant ID to use when authenticating a user through + :class:`~azure.identity.InteractiveBrowserCredential`. Defaults to the value of environment variable + AZURE_TENANT_ID, if any. If unspecified, users will authenticate in their home tenants. + :keyword str managed_identity_client_id: The client ID of a user-assigned managed identity. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, a system-assigned identity will be used. + :keyword str workload_identity_client_id: The client ID of an identity assigned to the pod. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, the pod's default identity will be used. + :keyword str workload_identity_tenant_id: Preferred tenant for :class:`~azure.identity.WorkloadIdentityCredential`. + Defaults to the value of environment variable AZURE_TENANT_ID, if any. + :keyword str interactive_browser_client_id: The client ID to be used in interactive browser credential. If not + specified, users will authenticate to an Azure development application. + :keyword str shared_cache_username: Preferred username for :class:`~azure.identity.SharedTokenCacheCredential`. + Defaults to the value of environment variable AZURE_USERNAME, if any. + :keyword str shared_cache_tenant_id: Preferred tenant for :class:`~azure.identity.SharedTokenCacheCredential`. + Defaults to the value of environment variable AZURE_TENANT_ID, if any. + :keyword str visual_studio_code_tenant_id: Tenant ID to use when authenticating with + :class:`~azure.identity.VisualStudioCodeCredential`. Defaults to the "Azure: Tenant" setting in VS Code's user + settings or, when that setting has no value, the "organizations" tenant, which supports only Azure Active + Directory work or school accounts. + :keyword int process_timeout: The timeout in seconds to use for developer credentials that run + subprocesses (e.g. AzureCliCredential, AzurePowerShellCredential). Defaults to **10** seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_default_credential] + :end-before: [END create_default_credential] + :language: python + :dedent: 4 + :caption: Create a DefaultAzureCredential. + """ + + def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-statements, too-many-locals + if "tenant_id" in kwargs: + raise TypeError("'tenant_id' is not supported in DefaultAzureCredential.") + + authority = kwargs.pop("authority", None) + + vscode_tenant_id = kwargs.pop( + "visual_studio_code_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + vscode_args = dict(kwargs) + if authority: + vscode_args["authority"] = authority + if vscode_tenant_id: + vscode_args["tenant_id"] = vscode_tenant_id + + authority = normalize_authority(authority) if authority else get_default_authority() + + interactive_browser_tenant_id = kwargs.pop( + "interactive_browser_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + + managed_identity_client_id = kwargs.pop( + "managed_identity_client_id", os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + ) + workload_identity_client_id = kwargs.pop("workload_identity_client_id", managed_identity_client_id) + workload_identity_tenant_id = kwargs.pop( + "workload_identity_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + interactive_browser_client_id = kwargs.pop("interactive_browser_client_id", None) + + shared_cache_username = kwargs.pop("shared_cache_username", os.environ.get(EnvironmentVariables.AZURE_USERNAME)) + shared_cache_tenant_id = kwargs.pop( + "shared_cache_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + + process_timeout = kwargs.pop("process_timeout", 10) + + exclude_workload_identity_credential = kwargs.pop("exclude_workload_identity_credential", False) + exclude_environment_credential = kwargs.pop("exclude_environment_credential", False) + exclude_managed_identity_credential = kwargs.pop("exclude_managed_identity_credential", False) + exclude_shared_token_cache_credential = kwargs.pop("exclude_shared_token_cache_credential", False) + exclude_visual_studio_code_credential = kwargs.pop("exclude_visual_studio_code_credential", True) + exclude_developer_cli_credential = kwargs.pop("exclude_developer_cli_credential", False) + exclude_cli_credential = kwargs.pop("exclude_cli_credential", False) + exclude_interactive_browser_credential = kwargs.pop("exclude_interactive_browser_credential", True) + exclude_powershell_credential = kwargs.pop("exclude_powershell_credential", False) + + credentials: List["TokenCredential"] = [] + if not exclude_environment_credential: + credentials.append(EnvironmentCredential(authority=authority, _within_dac=True, **kwargs)) + if not exclude_workload_identity_credential: + if all(os.environ.get(var) for var in EnvironmentVariables.WORKLOAD_IDENTITY_VARS): + client_id = workload_identity_client_id + credentials.append( + WorkloadIdentityCredential( + client_id=cast(str, client_id), + tenant_id=workload_identity_tenant_id, + file=os.environ[EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE], + **kwargs + ) + ) + if not exclude_managed_identity_credential: + credentials.append( + ManagedIdentityCredential( + client_id=managed_identity_client_id, + _exclude_workload_identity_credential=exclude_workload_identity_credential, + **kwargs + ) + ) + if not exclude_shared_token_cache_credential and SharedTokenCacheCredential.supported(): + try: + # username and/or tenant_id are only required when the cache contains tokens for multiple identities + shared_cache = SharedTokenCacheCredential( + username=shared_cache_username, tenant_id=shared_cache_tenant_id, authority=authority, **kwargs + ) + credentials.append(shared_cache) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.info("Shared token cache is unavailable: '%s'", ex) + if not exclude_visual_studio_code_credential: + credentials.append(VisualStudioCodeCredential(**vscode_args)) + if not exclude_cli_credential: + credentials.append(AzureCliCredential(process_timeout=process_timeout)) + if not exclude_powershell_credential: + credentials.append(AzurePowerShellCredential(process_timeout=process_timeout)) + if not exclude_developer_cli_credential: + credentials.append(AzureDeveloperCliCredential(process_timeout=process_timeout)) + if not exclude_interactive_browser_credential: + if interactive_browser_client_id: + credentials.append( + InteractiveBrowserCredential( + tenant_id=interactive_browser_tenant_id, client_id=interactive_browser_client_id, **kwargs + ) + ) + else: + credentials.append(InteractiveBrowserCredential(tenant_id=interactive_browser_tenant_id, **kwargs)) + + super(DefaultAzureCredential, self).__init__(*credentials) + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + token = self._successful_credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + _LOGGER.info( + "%s acquired a token from %s", self.__class__.__name__, self._successful_credential.__class__.__name__ + ) + return token + within_dac.set(True) + token = super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + within_dac.set(False) + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/device_code.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/device_code.py new file mode 100644 index 0000000000000000000000000000000000000000..8bb798d78b3a66e4c5ed2c483544c3479c89cd8f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/device_code.py @@ -0,0 +1,117 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from datetime import datetime +import time +from typing import Dict, Optional, Callable, Any + +from azure.core.exceptions import ClientAuthenticationError + +from .._constants import DEVELOPER_SIGN_ON_CLIENT_ID +from .._internal import InteractiveCredential, wrap_exceptions + + +class DeviceCodeCredential(InteractiveCredential): + """Authenticates users through the device code flow. + + When :func:`get_token` is called, this credential acquires a verification URL and code from Microsoft Entra ID. + A user must browse to the URL, enter the code, and authenticate with Microsoft Entra ID. If the user + authenticates successfully, the credential receives an access token. + + This credential is primarily useful for authenticating a user in an environment without a web browser, such as an + SSH session. If a web browser is available, :class:`~azure.identity.InteractiveBrowserCredential` is more + convenient because it automatically opens a browser to the login page. + + :param str client_id: client ID of the application users will authenticate to. When not specified users will + authenticate to an Azure development application. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str tenant_id: a Microsoft Entra tenant ID. Defaults to the "organizations" tenant, which can + authenticate work or school accounts. **Required for single-tenant applications.** + :keyword int timeout: seconds to wait for the user to authenticate. Defaults to the validity period of the + device code as set by Microsoft Entra ID, which also prevails when **timeout** is longer. + :keyword prompt_callback: A callback enabling control of how authentication + instructions are presented. Must accept arguments (``verification_uri``, ``user_code``, ``expires_on``): + + - ``verification_uri`` (str) the URL the user must visit + - ``user_code`` (str) the code the user must enter there + - ``expires_on`` (datetime.datetime) the UTC time at which the code will expire + If this argument isn't provided, the credential will print instructions to stdout. + :paramtype prompt_callback: Callable[str, str, ~datetime.datetime] + :keyword AuthenticationRecord authentication_record: :class:`AuthenticationRecord` returned by :func:`authenticate` + :keyword bool disable_automatic_authentication: if True, :func:`get_token` will raise + :class:`AuthenticationRequiredError` when user interaction is required to acquire a token. Defaults to False. + :keyword cache_persistence_options: configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword bool enable_support_logging: Enables additional support logging in the underlying MSAL library. + This logging potentially contains personally identifiable information and is intended to be used only for + troubleshooting purposes. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_device_code_credential] + :end-before: [END create_device_code_credential] + :language: python + :dedent: 4 + :caption: Create a DeviceCodeCredential. + """ + + def __init__( + self, + client_id: str = DEVELOPER_SIGN_ON_CLIENT_ID, + *, + timeout: Optional[int] = None, + prompt_callback: Optional[Callable[[str, str, datetime], None]] = None, + **kwargs: Any + ) -> None: + self._timeout = timeout + self._prompt_callback = prompt_callback + super(DeviceCodeCredential, self).__init__(client_id=client_id, **kwargs) + + @wrap_exceptions + def _request_token(self, *scopes: str, **kwargs: Any) -> Dict: + # MSAL requires scopes be a list + scopes = list(scopes) # type: ignore + + app = self._get_app(**kwargs) + flow = app.initiate_device_flow(scopes) + if "error" in flow: + raise ClientAuthenticationError( + message="Couldn't begin authentication: {}".format(flow.get("error_description") or flow.get("error")) + ) + + if self._prompt_callback: + self._prompt_callback( + flow["verification_uri"], flow["user_code"], datetime.utcfromtimestamp(flow["expires_at"]) + ) + else: + print(flow["message"]) + + if self._timeout is not None and self._timeout < flow["expires_in"]: + # user specified an effective timeout we will observe + deadline = int(time.time()) + self._timeout + result = app.acquire_token_by_device_flow( + flow, exit_condition=lambda flow: time.time() > deadline, claims_challenge=kwargs.get("claims") + ) + else: + # MSAL will stop polling when the device code expires + result = app.acquire_token_by_device_flow(flow, claims_challenge=kwargs.get("claims")) + + # raise for a timeout here because the error is particular to this class + if "access_token" not in result and result.get("error") == "authorization_pending": + raise ClientAuthenticationError(message="Timed out waiting for user to authenticate") + + # base class will raise for other errors + return result diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/environment.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..38e0240cbd879b82cafa2130e7484581f9b0b01f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/environment.py @@ -0,0 +1,151 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import Optional, Union, Any +from azure.core.credentials import AccessToken + +from .. import CredentialUnavailableError +from .._constants import EnvironmentVariables +from .._internal.decorators import log_get_token +from .certificate import CertificateCredential +from .client_secret import ClientSecretCredential +from .user_password import UsernamePasswordCredential + +EnvironmentCredentialTypes = Union[CertificateCredential, ClientSecretCredential, UsernamePasswordCredential] + +_LOGGER = logging.getLogger(__name__) + + +class EnvironmentCredential: + """A credential configured by environment variables. + + This credential is capable of authenticating as a service principal using a client secret or a certificate, or as + a user with a username and password. Configuration is attempted in this order, using these environment variables: + + Service principal with secret: + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its 'directory' ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + - **AZURE_CLIENT_SECRET**: one of the service principal's client secrets + - **AZURE_AUTHORITY_HOST**: authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud, which is the default + when no value is given. + + Service principal with certificate: + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its 'directory' ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + - **AZURE_CLIENT_CERTIFICATE_PATH**: path to a PEM or PKCS12 certificate file including the private key. + - **AZURE_CLIENT_CERTIFICATE_PASSWORD**: (optional) password of the certificate file, if any. + - **AZURE_AUTHORITY_HOST**: authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud, which is the default + when no value is given. + + User with username and password: + - **AZURE_CLIENT_ID**: the application's client ID + - **AZURE_USERNAME**: a username (usually an email address) + - **AZURE_PASSWORD**: that user's password + - **AZURE_TENANT_ID**: (optional) ID of the service principal's tenant. Also called its 'directory' ID. + If not provided, defaults to the 'organizations' tenant, which supports only Microsoft Entra work or + school accounts. + - **AZURE_AUTHORITY_HOST**: authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud, which is the default + when no value is given. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_environment_credential] + :end-before: [END create_environment_credential] + :language: python + :dedent: 4 + :caption: Create an EnvironmentCredential. + """ + + def __init__(self, **kwargs: Any) -> None: + self._credential: Optional[EnvironmentCredentialTypes] = None + + if all(os.environ.get(v) is not None for v in EnvironmentVariables.CLIENT_SECRET_VARS): + self._credential = ClientSecretCredential( + client_id=os.environ[EnvironmentVariables.AZURE_CLIENT_ID], + client_secret=os.environ[EnvironmentVariables.AZURE_CLIENT_SECRET], + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + **kwargs + ) + elif all(os.environ.get(v) is not None for v in EnvironmentVariables.CERT_VARS): + self._credential = CertificateCredential( + client_id=os.environ[EnvironmentVariables.AZURE_CLIENT_ID], + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + certificate_path=os.environ[EnvironmentVariables.AZURE_CLIENT_CERTIFICATE_PATH], + password=os.environ.get(EnvironmentVariables.AZURE_CLIENT_CERTIFICATE_PASSWORD), + **kwargs + ) + elif all(os.environ.get(v) is not None for v in EnvironmentVariables.USERNAME_PASSWORD_VARS): + self._credential = UsernamePasswordCredential( + client_id=os.environ[EnvironmentVariables.AZURE_CLIENT_ID], + username=os.environ[EnvironmentVariables.AZURE_USERNAME], + password=os.environ[EnvironmentVariables.AZURE_PASSWORD], + tenant_id=os.environ.get(EnvironmentVariables.AZURE_TENANT_ID), # optional for username/password auth + **kwargs + ) + + if self._credential: + _LOGGER.info("Environment is configured for %s", self._credential.__class__.__name__) + else: + expected_variables = set( + EnvironmentVariables.CERT_VARS + + EnvironmentVariables.CLIENT_SECRET_VARS + + EnvironmentVariables.USERNAME_PASSWORD_VARS + ) + set_variables = [v for v in expected_variables if v in os.environ] + if set_variables: + _LOGGER.log( + logging.INFO if kwargs.get("_within_dac") else logging.WARNING, + "Incomplete environment configuration for EnvironmentCredential. These variables are set: %s", + ", ".join(set_variables), + ) + else: + _LOGGER.info("No environment configuration found.") + + def __enter__(self): + if self._credential: + self._credential.__enter__() + return self + + def __exit__(self, *args): + if self._credential: + self._credential.__exit__(*args) + + def close(self) -> None: + """Close the credential's transport session.""" + self.__exit__() + + @log_get_token("EnvironmentCredential") + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + + :raises ~azure.identity.CredentialUnavailableError: environment variable configuration is incomplete + """ + if not self._credential: + message = ( + "EnvironmentCredential authentication unavailable. Environment variables are not fully configured.\n" + "Visit https://aka.ms/azsdk/python/identity/environmentcredential/troubleshoot to troubleshoot " + "this issue." + ) + raise CredentialUnavailableError(message=message) + return self._credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/imds.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/imds.py new file mode 100644 index 0000000000000000000000000000000000000000..748a7ce1216861c4312c710f092742a6c0b00cf3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/imds.py @@ -0,0 +1,123 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +from typing import Any, Optional, Dict + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError +from azure.core.pipeline.transport import HttpRequest +from azure.core.credentials import AccessToken + +from .. import CredentialUnavailableError +from .._constants import EnvironmentVariables +from .._internal import within_credential_chain +from .._internal.get_token_mixin import GetTokenMixin +from .._internal.managed_identity_client import ManagedIdentityClient + + +IMDS_AUTHORITY = "http://169.254.169.254" +IMDS_TOKEN_PATH = "/metadata/identity/oauth2/token" + +PIPELINE_SETTINGS = { + "connection_timeout": 2, + "retry_backoff_factor": 2, + "retry_backoff_max": 60, + "retry_on_status_codes": [404, 410, 429] + list(range(500, 600)), + "retry_status": 5, + "retry_total": 5, +} + + +def _get_request(scope: str, identity_config: Dict) -> HttpRequest: + url = ( + os.environ.get(EnvironmentVariables.AZURE_POD_IDENTITY_AUTHORITY_HOST, IMDS_AUTHORITY).strip("/") + + IMDS_TOKEN_PATH + ) + request = HttpRequest("GET", url) + request.format_parameters(dict({"api-version": "2018-02-01", "resource": scope}, **identity_config)) + return request + + +def _check_forbidden_response(ex: HttpResponseError) -> None: + """Special case handling for Docker Desktop. + + Docker Desktop proxies all HTTP traffic, and if the IMDS endpoint is unreachable, it + responds with a 403 with a message that contains "A socket operation was attempted to an unreachable network". + + :param ~azure.core.exceptions.HttpResponseError ex: The exception raised by the request + :raises ~azure.core.exceptions.CredentialUnavailableError: When the IMDS endpoint is unreachable + """ + if ex.status_code == 403: + if ex.message and "A socket operation was attempted to an unreachable network" in ex.message: + error_message = f"ManagedIdentityCredential authentication unavailable. Error: {ex.message}" + raise CredentialUnavailableError(message=error_message) from ex + + +class ImdsCredential(GetTokenMixin): + def __init__(self, **kwargs: Any) -> None: + super(ImdsCredential, self).__init__() + + self._client = ManagedIdentityClient(_get_request, **dict(PIPELINE_SETTINGS, **kwargs)) + if EnvironmentVariables.AZURE_POD_IDENTITY_AUTHORITY_HOST in os.environ: + self._endpoint_available: Optional[bool] = True + else: + self._endpoint_available = None + self._user_assigned_identity = "client_id" in kwargs or "identity_config" in kwargs + + def __enter__(self): + self._client.__enter__() + return self + + def __exit__(self, *args): + self._client.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + return self._client.get_cached_token(*scopes) + + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + + if within_credential_chain.get() and not self._endpoint_available: + # If within a chain (e.g. DefaultAzureCredential), we do a quick check to see if the IMDS endpoint + # is available to avoid hanging for a long time if the endpoint isn't available. + try: + self._client.request_token(*scopes, connection_timeout=1, retry_total=0) + self._endpoint_available = True + except HttpResponseError as ex: + # IMDS responded + _check_forbidden_response(ex) + self._endpoint_available = True + except Exception as ex: # pylint:disable=broad-except + error_message = ( + "ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint." + ) + raise CredentialUnavailableError(error_message) from ex + + try: + token = self._client.request_token(*scopes, headers={"Metadata": "true"}) + except HttpResponseError as ex: + # 400 in response to a token request indicates managed identity is disabled, + # or the identity with the specified client_id is not available + if ex.status_code == 400: + error_message = "ManagedIdentityCredential authentication unavailable. " + if self._user_assigned_identity: + error_message += "The requested identity has not been assigned to this resource." + else: + error_message += "No identity has been assigned to this resource." + + if ex.message: + error_message += f" Error: {ex.message}" + + raise CredentialUnavailableError(message=error_message) from ex + + _check_forbidden_response(ex) + # any other error is unexpected + raise ClientAuthenticationError(message=ex.message, response=ex.response) from ex + except Exception as ex: # pylint:disable=broad-except + # if anything else was raised, assume the endpoint is unavailable + error_message = "ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint." + raise CredentialUnavailableError(error_message) from ex + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/managed_identity.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/managed_identity.py new file mode 100644 index 0000000000000000000000000000000000000000..82301cc36c7ea699295b500a7aa6febc1580185d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/managed_identity.py @@ -0,0 +1,137 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import Optional, TYPE_CHECKING, Any + +from azure.core.credentials import AccessToken +from .. import CredentialUnavailableError +from .._constants import EnvironmentVariables +from .._internal.decorators import log_get_token + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + +_LOGGER = logging.getLogger(__name__) + + +class ManagedIdentityCredential: + """Authenticates with an Azure managed identity in any hosting environment which supports managed identities. + + This credential defaults to using a system-assigned identity. To configure a user-assigned identity, use one of + the keyword arguments. See `Microsoft Entra ID documentation + `_ for more + information about configuring managed identity for applications. + + :keyword str client_id: a user-assigned identity's client ID or, when using Pod Identity, the client ID of an Azure + AD app registration. This argument is supported in all hosting environments. + :keyword identity_config: a mapping ``{parameter_name: value}`` specifying a user-assigned identity by its object + or resource ID, for example ``{"object_id": "..."}``. Check the documentation for your hosting environment to + learn what values it expects. + :paramtype identity_config: Mapping[str, str] + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_managed_identity_credential] + :end-before: [END create_managed_identity_credential] + :language: python + :dedent: 4 + :caption: Create a ManagedIdentityCredential. + """ + + def __init__(self, **kwargs: Any) -> None: + self._credential = None # type: Optional[TokenCredential] + exclude_workload_identity = kwargs.pop("_exclude_workload_identity_credential", False) + if os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT): + if os.environ.get(EnvironmentVariables.IDENTITY_HEADER): + if os.environ.get(EnvironmentVariables.IDENTITY_SERVER_THUMBPRINT): + _LOGGER.info("%s will use Service Fabric managed identity", self.__class__.__name__) + from .service_fabric import ServiceFabricCredential + + self._credential = ServiceFabricCredential(**kwargs) + else: + _LOGGER.info("%s will use App Service managed identity", self.__class__.__name__) + from .app_service import AppServiceCredential + + self._credential = AppServiceCredential(**kwargs) + elif os.environ.get(EnvironmentVariables.IMDS_ENDPOINT): + _LOGGER.info("%s will use Azure Arc managed identity", self.__class__.__name__) + from .azure_arc import AzureArcCredential + + self._credential = AzureArcCredential(**kwargs) + elif os.environ.get(EnvironmentVariables.MSI_ENDPOINT): + if os.environ.get(EnvironmentVariables.MSI_SECRET): + _LOGGER.info("%s will use Azure ML managed identity", self.__class__.__name__) + from .azure_ml import AzureMLCredential + + self._credential = AzureMLCredential(**kwargs) + else: + _LOGGER.info("%s will use Cloud Shell managed identity", self.__class__.__name__) + from .cloud_shell import CloudShellCredential + + self._credential = CloudShellCredential(**kwargs) + elif ( + all(os.environ.get(var) for var in EnvironmentVariables.WORKLOAD_IDENTITY_VARS) + and not exclude_workload_identity + ): + _LOGGER.info("%s will use workload identity", self.__class__.__name__) + from .workload_identity import WorkloadIdentityCredential + + client_id = kwargs.pop("client_id", None) or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + if not client_id: + raise ValueError('Configure the environment with a client ID or pass a value for "client_id" argument') + + self._credential = WorkloadIdentityCredential( + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + client_id=client_id, + file=os.environ[EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE], + **kwargs + ) + else: + from .imds import ImdsCredential + + _LOGGER.info("%s will use IMDS", self.__class__.__name__) + self._credential = ImdsCredential(**kwargs) + + def __enter__(self): + self._credential.__enter__() + return self + + def __exit__(self, *args): + self._credential.__exit__(*args) + + def close(self) -> None: + """Close the credential's transport session.""" + self.__exit__() + + @log_get_token("ManagedIdentityCredential") + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: not used by this credential; any value provided will be ignored. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: managed identity isn't available in the hosting environment + """ + + if not self._credential: + raise CredentialUnavailableError( + message="No managed identity endpoint found. \n" + "The Target Azure platform could not be determined from environment variables. \n" + "Visit https://aka.ms/azsdk/python/identity/managedidentitycredential/troubleshoot to " + "troubleshoot this issue." + ) + return self._credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/on_behalf_of.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/on_behalf_of.py new file mode 100644 index 0000000000000000000000000000000000000000..b1c2ea7d314e2148db5f11ad52b80272b832180a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/on_behalf_of.py @@ -0,0 +1,127 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import time +from typing import Any, Optional + +import msal + +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError + +from .certificate import get_client_credential +from .._internal.decorators import wrap_exceptions +from .._internal.get_token_mixin import GetTokenMixin +from .._internal.interactive import _build_auth_record +from .._internal.msal_credentials import MsalCredential +from .. import AuthenticationRecord + + +class OnBehalfOfCredential(MsalCredential, GetTokenMixin): + """Authenticates a service principal via the on-behalf-of flow. + + This flow is typically used by middle-tier services that authorize requests to other services with a delegated + user identity. Because this is not an interactive authentication flow, an application using it must have admin + consent for any delegated permissions before requesting tokens for them. See `Microsoft Entra ID documentation + `_ for a more detailed + description of the on-behalf-of flow. + + :param str tenant_id: ID of the service principal's tenant. Also called its "directory" ID. + :param str client_id: The service principal's client ID + :keyword str client_secret: Optional. A client secret to authenticate the service principal. + Either **client_secret** or **client_certificate** must be provided. + :keyword bytes client_certificate: Optional. The bytes of a certificate in PEM or PKCS12 format including + the private key to authenticate the service principal. Either **client_secret** or **client_certificate** must + be provided. + :keyword str user_assertion: Required. The access token the credential will use as the user assertion when + requesting on-behalf-of tokens + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword password: A certificate password. Used only when **client_certificate** is provided. If this value + is a unicode string, it will be encoded as UTF-8. If the certificate requires a different encoding, pass + appropriately encoded bytes instead. + :paramtype password: str or bytes + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_on_behalf_of_credential] + :end-before: [END create_on_behalf_of_credential] + :language: python + :dedent: 4 + :caption: Create an OnBehalfOfCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, **kwargs: Any) -> None: + self._assertion = kwargs.pop("user_assertion", None) + if not self._assertion: + raise TypeError('"user_assertion" is required.') + client_certificate = kwargs.pop("client_certificate", None) + client_secret = kwargs.pop("client_secret", None) + + if client_certificate: + if client_secret: + raise ValueError('Specifying both "client_certificate" and "client_secret" is not valid.') + try: + credential = get_client_credential( + certificate_path=None, password=kwargs.pop("password", None), certificate_data=client_certificate + ) + except ValueError as ex: + # client_certificate isn't a valid cert. + message = '"client_certificate" is not a valid certificate in PEM or PKCS12 format' + raise ValueError(message) from ex + elif client_secret: + credential = client_secret + else: + raise TypeError('Either "client_certificate" or "client_secret" must be provided') + + super(OnBehalfOfCredential, self).__init__( + client_id=client_id, client_credential=credential, tenant_id=tenant_id, **kwargs + ) + self._auth_record: Optional[AuthenticationRecord] = None + + @wrap_exceptions + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + if self._auth_record: + claims = kwargs.get("claims") + app = self._get_app(**kwargs) + for account in app.get_accounts(username=self._auth_record.username): + if account.get("home_account_id") != self._auth_record.home_account_id: + continue + + now = int(time.time()) + result = app.acquire_token_silent_with_error(list(scopes), account=account, claims_challenge=claims) + if result and "access_token" in result and "expires_in" in result: + return AccessToken(result["access_token"], now + int(result["expires_in"])) + + return None + + @wrap_exceptions + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + app: msal.ConfidentialClientApplication = self._get_app(**kwargs) + request_time = int(time.time()) + result = app.acquire_token_on_behalf_of(self._assertion, list(scopes), claims_challenge=kwargs.get("claims")) + if "access_token" not in result or "expires_in" not in result: + message = "Authentication failed: {}".format(result.get("error_description") or result.get("error")) + response = self._client.get_error_response(result) + raise ClientAuthenticationError(message=message, response=response) + + try: + self._auth_record = _build_auth_record(result) + except ClientAuthenticationError: + pass # non-fatal; we'll use the assertion again next time instead of a refresh token + + return AccessToken(result["access_token"], request_time + int(result["expires_in"])) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/service_fabric.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/service_fabric.py new file mode 100644 index 0000000000000000000000000000000000000000..b4081fbf013bec4e8ff2e816efb847c2bcb354fe --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/service_fabric.py @@ -0,0 +1,46 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Dict, Optional, Any + +from azure.core.pipeline.transport import HttpRequest + +from .._constants import EnvironmentVariables +from .._internal.managed_identity_base import ManagedIdentityBase +from .._internal.managed_identity_client import ManagedIdentityClient + + +class ServiceFabricCredential(ManagedIdentityBase): + def get_client(self, **kwargs) -> Optional[ManagedIdentityClient]: + client_args = _get_client_args(**kwargs) + if client_args: + return ManagedIdentityClient(**client_args) + return None + + def get_unavailable_message(self) -> str: + return "Service Fabric managed identity configuration not found in environment" + + +def _get_client_args(**kwargs: Any) -> Optional[Dict]: + url = os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT) + secret = os.environ.get(EnvironmentVariables.IDENTITY_HEADER) + thumbprint = os.environ.get(EnvironmentVariables.IDENTITY_SERVER_THUMBPRINT) + if not (url and secret and thumbprint): + # Service Fabric managed identity isn't available in this environment + return None + + return dict( + kwargs, + base_headers={"Secret": secret}, + connection_verify=False, + request_factory=functools.partial(_get_request, url), + ) + + +def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: + request = HttpRequest("GET", url) + request.format_parameters(dict({"api-version": "2019-07-01-preview", "resource": scope}, **identity_config)) + return request diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/shared_cache.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/shared_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..8bac28dc809f9665cf97b6eec00773d12094f414 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/shared_cache.py @@ -0,0 +1,140 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import TYPE_CHECKING, Any, Optional +from azure.core.credentials import AccessToken + +from .silent import SilentAuthenticationCredential +from .. import CredentialUnavailableError +from .._constants import DEVELOPER_SIGN_ON_CLIENT_ID +from .._internal import AadClient, AadClientBase +from .._internal.decorators import log_get_token +from .._internal.shared_token_cache import NO_TOKEN, SharedTokenCacheBase + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class SharedTokenCacheCredential: + """Authenticates using tokens in the local cache shared between Microsoft applications. + + :param str username: Username (typically an email address) of the user to authenticate as. This is used when the + local cache contains tokens for multiple identities. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str tenant_id: a Microsoft Entra tenant ID. Used to select an account when the cache contains + tokens for multiple identities. + :keyword AuthenticationRecord authentication_record: an authentication record returned by a user credential such as + :class:`DeviceCodeCredential` or :class:`InteractiveBrowserCredential` + :keyword cache_persistence_options: configuration for persistent token caching. If not provided, the credential + will use the persistent cache shared by Microsoft development applications + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + """ + + def __init__(self, username: Optional[str] = None, **kwargs: Any) -> None: + if "authentication_record" in kwargs: + self._credential = SilentAuthenticationCredential(**kwargs) # type: TokenCredential + else: + self._credential = _SharedTokenCacheCredential(username=username, **kwargs) + + def __enter__(self): + self._credential.__enter__() + return self + + def __exit__(self, *args): + self._credential.__exit__(*args) + + def close(self) -> None: + """Close the credential's transport session.""" + self.__exit__() + + @log_get_token("SharedTokenCacheCredential") + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Get an access token for `scopes` from the shared cache. + + If no access token is cached, attempt to acquire one using a cached refresh token. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure + :keyword str tenant_id: not used by this credential; any value provided will be ignored. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the cache is unavailable or contains insufficient user + information + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + return self._credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + @staticmethod + def supported() -> bool: + """Whether the shared token cache is supported on the current platform. + + :return: True if the shared token cache is supported on the current platform, otherwise False. + :rtype: bool + """ + return SharedTokenCacheBase.supported() + + +class _SharedTokenCacheCredential(SharedTokenCacheBase): + """The original SharedTokenCacheCredential, which doesn't use msal.ClientApplication""" + + def __enter__(self): + if self._client: + self._client.__enter__() + return self + + def __exit__(self, *args): + if self._client: + self._client.__exit__(*args) + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + if not scopes: + raise ValueError("'get_token' requires at least one scope") + + if not self._client_initialized: + self._initialize_client() + + is_cae = bool(kwargs.get("enable_cae", False)) + token_cache = self._cae_cache if is_cae else self._cache + + # Try to load the cache if it is None. + if not token_cache: + token_cache = self._initialize_cache(is_cae=is_cae) + + # If the cache is still None, raise an error. + if not token_cache: + raise CredentialUnavailableError(message="Shared token cache unavailable") + + account = self._get_account(self._username, self._tenant_id, is_cae=is_cae) + + token = self._get_cached_access_token(scopes, account, is_cae=is_cae) + if token: + return token + + # try each refresh token, returning the first access token acquired + for refresh_token in self._get_refresh_tokens(account, is_cae=is_cae): + token = self._client.obtain_token_by_refresh_token( + scopes, refresh_token, claims=claims, tenant_id=tenant_id, **kwargs + ) + return token + + raise CredentialUnavailableError(message=NO_TOKEN.format(account.get("username"))) + + def _get_auth_client(self, **kwargs: Any) -> AadClientBase: + return AadClient(client_id=DEVELOPER_SIGN_ON_CLIENT_ID, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/silent.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/silent.py new file mode 100644 index 0000000000000000000000000000000000000000..ec15d0435cfa84d5ab284302e46317e9867d8c59 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/silent.py @@ -0,0 +1,164 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import platform +import time +from typing import Dict, Optional, Any + +from msal import PublicClientApplication, TokenCache + +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError + +from .. import CredentialUnavailableError +from .._internal import resolve_tenant, validate_tenant_id, within_dac +from .._internal.decorators import wrap_exceptions +from .._internal.msal_client import MsalClient +from .._internal.shared_token_cache import NO_TOKEN +from .._persistent_cache import _load_persistent_cache, TokenCachePersistenceOptions +from .. import AuthenticationRecord + + +class SilentAuthenticationCredential: + """Internal class for authenticating from the default shared cache given an AuthenticationRecord. + + :param authentication_record: an AuthenticationRecord from which to authenticate + :type authentication_record: ~azure.identity.AuthenticationRecord + :keyword str tenant_id: tenant ID of the application the credential is authenticating for. Defaults to the tenant + """ + + def __init__( + self, authentication_record: AuthenticationRecord, *, tenant_id: Optional[str] = None, **kwargs + ) -> None: + self._auth_record = authentication_record + + # authenticate in the tenant that produced the record unless "tenant_id" specifies another + self._tenant_id = tenant_id or self._auth_record.tenant_id + validate_tenant_id(self._tenant_id) + self._cache = kwargs.pop("_cache", None) + self._cae_cache = kwargs.pop("_cae_cache", None) + + self._cache_persistence_options = kwargs.pop("cache_persistence_options", None) + + self._client_applications: Dict[str, PublicClientApplication] = {} + self._cae_client_applications: Dict[str, PublicClientApplication] = {} + + self._additionally_allowed_tenants = kwargs.pop("additionally_allowed_tenants", []) + self._client = MsalClient(**kwargs) + + def __enter__(self): + self._client.__enter__() + return self + + def __exit__(self, *args): + self._client.__exit__(*args) + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + if not scopes: + raise ValueError('"get_token" requires at least one scope') + + token_cache = self._cae_cache if kwargs.get("enable_cae") else self._cache + + # Try to load the cache if it is None. + if not token_cache: + token_cache = self._initialize_cache(is_cae=bool(kwargs.get("enable_cae"))) + + # If the cache is still None, raise an error. + if not token_cache: + if within_dac.get(): + raise CredentialUnavailableError(message="Shared token cache unavailable") + raise ClientAuthenticationError(message="Shared token cache unavailable") + + return self._acquire_token_silent(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + def _initialize_cache(self, is_cae: bool = False) -> Optional[TokenCache]: + + # If no cache options were provided, the default cache will be used. This credential accepts the + # user's default cache regardless of whether it's encrypted. It doesn't create a new cache. If the + # default cache exists, the user must have created it earlier. If it's unencrypted, the user must + # have allowed that. + cache_options = self._cache_persistence_options or TokenCachePersistenceOptions(allow_unencrypted_storage=True) + + if platform.system() not in {"Darwin", "Linux", "Windows"}: + raise CredentialUnavailableError(message="Shared token cache is not supported on this platform.") + + if not self._cache and not is_cae: + try: + self._cache = _load_persistent_cache(cache_options, is_cae) + except Exception: # pylint:disable=broad-except + return None + + if not self._cae_cache and is_cae: + try: + self._cae_cache = _load_persistent_cache(cache_options, is_cae) + except Exception: # pylint:disable=broad-except + return None + + return self._cae_cache if is_cae else self._cache + + def _get_client_application(self, **kwargs: Any): + tenant_id = resolve_tenant( + self._tenant_id, additionally_allowed_tenants=self._additionally_allowed_tenants, **kwargs + ) + + client_applications_map = self._client_applications + capabilities = None + token_cache = self._cache + + if kwargs.get("enable_cae"): + client_applications_map = self._cae_client_applications + # CP1 = can handle claims challenges (CAE) + capabilities = ["CP1"] + token_cache = self._cae_cache + + if tenant_id not in client_applications_map: + client_applications_map[tenant_id] = PublicClientApplication( + client_id=self._auth_record.client_id, + authority="https://{}/{}".format(self._auth_record.authority, tenant_id), + token_cache=token_cache, + http_client=self._client, + client_capabilities=capabilities, + ) + return client_applications_map[tenant_id] + + @wrap_exceptions + def _acquire_token_silent(self, *scopes: str, **kwargs: Any) -> AccessToken: + """Silently acquire a token from MSAL. + + :param str scopes: desired scopes for the access token + :return: an access token + :rtype: ~azure.core.credentials.AccessToken + """ + + result = None + + client_application = self._get_client_application(**kwargs) + accounts_for_user = client_application.get_accounts(username=self._auth_record.username) + if not accounts_for_user: + raise CredentialUnavailableError("The cache contains no account matching the given AuthenticationRecord.") + + for account in accounts_for_user: + if account.get("home_account_id") != self._auth_record.home_account_id: + continue + + now = int(time.time()) + result = client_application.acquire_token_silent_with_error( + list(scopes), account=account, claims_challenge=kwargs.get("claims") + ) + if result and "access_token" in result and "expires_in" in result: + return AccessToken(result["access_token"], now + int(result["expires_in"])) + + # if we get this far, the cache contained a matching account but MSAL failed to authenticate it silently + if result: + # cache contains a matching refresh token but STS returned an error response when MSAL tried to use it + message = "Token acquisition failed" + details = result.get("error_description") or result.get("error") + if details: + message += ": {}".format(details) + raise ClientAuthenticationError(message=message) + + # cache doesn't contain a matching refresh (or access) token + raise CredentialUnavailableError(message=NO_TOKEN.format(self._auth_record.username)) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/user_password.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/user_password.py new file mode 100644 index 0000000000000000000000000000000000000000..f38a9ab625ea24bddebbdbb14aeee91f7684a763 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/user_password.py @@ -0,0 +1,79 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Dict + +from .._internal import InteractiveCredential, wrap_exceptions + + +class UsernamePasswordCredential(InteractiveCredential): + """Authenticates a user with a username and password. + + In general, Microsoft doesn't recommend this kind of authentication, because it's less secure than other + authentication flows. + + Authentication with this credential is not interactive, so it is **not compatible with any form of + multi-factor authentication or consent prompting**. The application must already have consent from the user or + a directory admin. + + This credential can only authenticate work and school accounts; Microsoft accounts are not supported. + See `Microsoft Entra ID documentation + `_ for more information about + account types. + + :param str client_id: The application's client ID + :param str username: The user's username (usually an email address) + :param str password: The user's password + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str tenant_id: Tenant ID or a domain associated with a tenant. If not provided, defaults to the + "organizations" tenant, which supports only Microsoft Entra work or school accounts. + :keyword cache_persistence_options: Configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword bool enable_support_logging: Enables additional support logging in the underlying MSAL library. + This logging potentially contains personally identifiable information and is intended to be used only for + troubleshooting purposes. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_username_password_credential] + :end-before: [END create_username_password_credential] + :language: python + :dedent: 4 + :caption: Create a UsernamePasswordCredential. + """ + + def __init__(self, client_id: str, username: str, password: str, **kwargs: Any) -> None: + # The base class will accept an AuthenticationRecord, allowing this credential to authenticate silently the + # first time it's asked for a token. However, we want to ensure this first authentication is not silent, to + # validate the given password. This class therefore doesn't document the authentication_record argument, and we + # discard it here. + kwargs.pop("authentication_record", None) + super(UsernamePasswordCredential, self).__init__(client_id=client_id, **kwargs) + self._username = username + self._password = password + + @wrap_exceptions + def _request_token(self, *scopes: str, **kwargs: Any) -> Dict: + app = self._get_app(**kwargs) + return app.acquire_token_by_username_password( + username=self._username, + password=self._password, + scopes=list(scopes), + claims_challenge=kwargs.get("claims"), + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/vscode.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/vscode.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe5eb0c13e1f168b057b394f7542f4f7684fd9d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/vscode.py @@ -0,0 +1,187 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import os +import sys +from typing import cast, Any, Dict, Optional + +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError +from .._exceptions import CredentialUnavailableError +from .._constants import AzureAuthorityHosts, AZURE_VSCODE_CLIENT_ID, EnvironmentVariables +from .._internal import normalize_authority, validate_tenant_id, within_dac +from .._internal.aad_client import AadClient, AadClientBase +from .._internal.get_token_mixin import GetTokenMixin +from .._internal.decorators import log_get_token + +if sys.platform.startswith("win"): + from .._internal.win_vscode_adapter import get_refresh_token, get_user_settings +elif sys.platform.startswith("darwin"): + from .._internal.macos_vscode_adapter import get_refresh_token, get_user_settings +else: + from .._internal.linux_vscode_adapter import get_refresh_token, get_user_settings + + +class _VSCodeCredentialBase(abc.ABC): + def __init__(self, **kwargs: Any) -> None: + super(_VSCodeCredentialBase, self).__init__() + + user_settings = get_user_settings() + self._cloud = user_settings.get("azure.cloud", "AzureCloud") + self._refresh_token = None + self._unavailable_reason = "" + + self._client = kwargs.get("_client") + if not self._client: + self._initialize(user_settings, **kwargs) + if not (self._client or self._unavailable_reason): + self._unavailable_reason = "Initialization failed" + + @abc.abstractmethod + def _get_client(self, **kwargs: Any) -> AadClientBase: + pass + + def _get_refresh_token(self) -> str: + if not self._refresh_token: + self._refresh_token = get_refresh_token(self._cloud) + if not self._refresh_token: + message = ( + "Failed to get Azure user details from Visual Studio Code. " + "Currently, the VisualStudioCodeCredential only works with the Azure " + "Account extension version 0.9.11 and earlier. A long-term fix is in " + "progress, see https://github.com/Azure/azure-sdk-for-python/issues/25713" + ) + raise CredentialUnavailableError(message=message) + return self._refresh_token + + def _initialize(self, vscode_user_settings: Dict, **kwargs: Any) -> None: + """Build a client from kwargs merged with VS Code user settings. + + The first stable version of this credential defaulted to Public Cloud and the "organizations" + tenant when it failed to read VS Code user settings. That behavior is preserved here. + + :param dict vscode_user_settings: VS Code user settings + """ + + # Precedence for authority: + # 1) VisualStudioCodeCredential(authority=...) + # 2) $AZURE_AUTHORITY_HOST + # 3) authority matching VS Code's "azure.cloud" setting + # 4) default: Public Cloud + authority = kwargs.pop("authority", None) or os.environ.get(EnvironmentVariables.AZURE_AUTHORITY_HOST) + if not authority: + # the application didn't specify an authority, so we figure it out from VS Code settings + if self._cloud == "AzureCloud": + authority = AzureAuthorityHosts.AZURE_PUBLIC_CLOUD + elif self._cloud == "AzureChinaCloud": + authority = AzureAuthorityHosts.AZURE_CHINA + elif self._cloud == "AzureGermanCloud": + authority = AzureAuthorityHosts.AZURE_GERMANY + elif self._cloud == "AzureUSGovernment": + authority = AzureAuthorityHosts.AZURE_GOVERNMENT + else: + # If the value is anything else ("AzureCustomCloud" is the only other known value), + # we need the user to provide the authority because VS Code has no setting for it and + # we can't guess confidently. + self._unavailable_reason = ( + 'VS Code is configured to use a custom cloud. Set keyword argument "authority"' + + ' with the Microsoft Entra endpoint for cloud "{}"'.format(self._cloud) + ) + return + + # Precedence for tenant ID: + # 1) VisualStudioCodeCredential(tenant_id=...) + # 2) "azure.tenant" in VS Code user settings + # 3) default: organizations + tenant_id = kwargs.pop("tenant_id", None) or vscode_user_settings.get("azure.tenant", "organizations") + validate_tenant_id(tenant_id) + if tenant_id.lower() == "adfs": + self._unavailable_reason = "VisualStudioCodeCredential authentication unavailable. ADFS is not supported." + return + + self._client = self._get_client( + authority=normalize_authority(authority), client_id=AZURE_VSCODE_CLIENT_ID, tenant_id=tenant_id, **kwargs + ) + + +class VisualStudioCodeCredential(_VSCodeCredentialBase, GetTokenMixin): + """Authenticates as the Azure user signed in to Visual Studio Code via the 'Azure Account' extension. + + It's a `known issue `_ that this credential doesn't + work with `Azure Account extension `_ + versions newer than **0.9.11**. A long-term fix to this problem is in progress. In the meantime, consider + authenticating with :class:`AzureCliCredential`. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com". + This argument is required for a custom cloud and usually unnecessary otherwise. Defaults to the authority + matching the "Azure: Cloud" setting in VS Code's user settings or, when that setting has no value, the + authority for Azure Public Cloud. + :keyword str tenant_id: ID of the tenant the credential should authenticate in. Defaults to the "Azure: Tenant" + setting in VS Code's user settings or, when that setting has no value, the "organizations" tenant, which + supports only Microsoft Entra work or school accounts. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + """ + + def __enter__(self): + if self._client: + self._client.__enter__() + return self + + def __exit__(self, *args): + if self._client: + self._client.__exit__(*args) + + def close(self) -> None: + """Close the credential's transport session.""" + self.__exit__() + + @log_get_token("VSCodeCredential") + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes` as the user currently signed in to Visual Studio Code. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual + Studio Code + """ + if self._unavailable_reason: + error_message = ( + self._unavailable_reason + "\n" + "Visit https://aka.ms/azsdk/python/identity/vscodecredential/troubleshoot" + " to troubleshoot this issue." + ) + raise CredentialUnavailableError(message=error_message) + if within_dac.get(): + try: + token = super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + return token + except ClientAuthenticationError as ex: + raise CredentialUnavailableError(message=ex.message) from ex + return super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + self._client = cast(AadClient, self._client) + return self._client.get_cached_access_token(scopes, **kwargs) + + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + refresh_token = self._get_refresh_token() + self._client = cast(AadClient, self._client) + return self._client.obtain_token_by_refresh_token(scopes, refresh_token, **kwargs) + + def _get_client(self, **kwargs: Any) -> AadClient: + return AadClient(**kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/workload_identity.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/workload_identity.py new file mode 100644 index 0000000000000000000000000000000000000000..ff6a9241ac699eb17108b6bf7213c4bdf4111da8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_credentials/workload_identity.py @@ -0,0 +1,94 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import time +from typing import Any +from typing import Optional + +from .client_assertion import ClientAssertionCredential +from .._constants import EnvironmentVariables + + +class TokenFileMixin: + def __init__(self, token_file_path: str, **_: Any) -> None: + super(TokenFileMixin, self).__init__() + self._jwt = "" + self._last_read_time = 0 + self._token_file_path = token_file_path + + def _get_service_account_token(self) -> str: + now = int(time.time()) + if now - self._last_read_time > 600: + with open(self._token_file_path, encoding="utf-8") as f: + self._jwt = f.read() + self._last_read_time = now + return self._jwt + + +class WorkloadIdentityCredential(ClientAssertionCredential, TokenFileMixin): + """Authenticates using Microsoft Entra Workload ID. + + Workload identity authentication is a feature in Azure that allows applications running on virtual machines (VMs) + to access other Azure resources without the need for a service principal or managed identity. With workload + identity authentication, applications authenticate themselves using their own identity, rather than using a shared + service principal or managed identity. Under the hood, workload identity authentication uses the concept of Service + Account Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using + workload identity authentication, you can avoid the need to manage and rotate service principals or managed + identities for each application on each VM. Additionally, because SACs are created automatically and managed by + Azure, you don't need to worry about storing and securing sensitive credentials themselves. + + The WorkloadIdentityCredential supports Azure workload identity authentication on Azure Kubernetes and acquires + a token using the service account credentials available in the Azure Kubernetes environment. Refer + to `this workload identity overview `__ + for more information. + + :keyword str tenant_id: ID of the application's Microsoft Entra tenant. Also called its "directory" ID. + :keyword str client_id: The client ID of a Microsoft Entra app registration. + :keyword str token_file_path: The path to a file containing a Kubernetes service account token that authenticates + the identity. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START workload_identity_credential] + :end-before: [END workload_identity_credential] + :language: python + :dedent: 4 + :caption: Create a WorkloadIdentityCredential. + """ + + def __init__( + self, + *, + tenant_id: Optional[str] = None, + client_id: Optional[str] = None, + token_file_path: Optional[str] = None, + **kwargs: Any, + ) -> None: + tenant_id = tenant_id or os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + client_id = client_id or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + token_file_path = token_file_path or os.environ.get(EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE) + if not tenant_id: + raise ValueError( + "'tenant_id' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_TENANT_ID} environment variable" + ) + if not client_id: + raise ValueError( + "'client_id' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_CLIENT_ID} environment variable" + ) + if not token_file_path: + raise ValueError( + "'token_file_path' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE} environment variable" + ) + super(WorkloadIdentityCredential, self).__init__( + tenant_id=tenant_id, + client_id=client_id, + func=self._get_service_account_token, + token_file_path=token_file_path, + **kwargs, + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7e5f1aa40385a8faff9d089a1b7575a6400e1627 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/__init__.py @@ -0,0 +1,56 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from .aad_client import AadClient +from .aad_client_base import AadClientBase +from .auth_code_redirect_handler import AuthCodeRedirectServer +from .aadclient_certificate import AadClientCertificate +from .decorators import wrap_exceptions +from .interactive import InteractiveCredential +from .utils import ( + get_default_authority, + normalize_authority, + resolve_tenant, + validate_scope, + validate_tenant_id, + within_credential_chain, + within_dac, +) + + +def _scopes_to_resource(*scopes) -> str: + """Convert a AADv2 scope to an AADv1 resource. + + :param str scopes: scope to convert + :return: the first scope, converted to an AADv1 resource + :rtype: str + :raises: ValueError if scopes is empty or contains more than one scope + """ + + if len(scopes) != 1: + raise ValueError("This credential requires exactly one scope per token request.") + + resource = scopes[0] + if resource.endswith("/.default"): + resource = resource[: -len("/.default")] + + return resource + + +__all__ = [ + "_scopes_to_resource", + "AadClient", + "AadClientBase", + "AuthCodeRedirectServer", + "AadClientCertificate", + "get_default_authority", + "InteractiveCredential", + "normalize_authority", + "resolve_tenant", + "validate_scope", + "within_credential_chain", + "within_dac", + "wrap_exceptions", + "validate_tenant_id", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/aad_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/aad_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b2bf39732feb658054602f0dba7517029f799ca2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/aad_client.py @@ -0,0 +1,74 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import time +from typing import Iterable, Union, Optional, Any + +from azure.core.credentials import AccessToken +from azure.core.pipeline import Pipeline +from azure.core.pipeline.transport import HttpRequest +from .aad_client_base import AadClientBase +from .aadclient_certificate import AadClientCertificate +from .pipeline import build_pipeline + + +class AadClient(AadClientBase): + def __enter__(self): + self._pipeline.__enter__() + return self + + def __exit__(self, *args): + self._pipeline.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def obtain_token_by_authorization_code( + self, scopes: Iterable[str], code: str, redirect_uri: str, client_secret: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + request = self._get_auth_code_request( + scopes=scopes, code=code, redirect_uri=redirect_uri, client_secret=client_secret, **kwargs + ) + return self._run_pipeline(request, **kwargs) + + def obtain_token_by_client_certificate( + self, scopes: Iterable[str], certificate: AadClientCertificate, **kwargs: Any + ) -> AccessToken: + request = self._get_client_certificate_request(scopes, certificate, **kwargs) + return self._run_pipeline(request, **kwargs) + + def obtain_token_by_client_secret(self, scopes: Iterable[str], secret: str, **kwargs: Any) -> AccessToken: + request = self._get_client_secret_request(scopes, secret, **kwargs) + return self._run_pipeline(request, **kwargs) + + def obtain_token_by_jwt_assertion(self, scopes: Iterable[str], assertion: str, **kwargs: Any) -> AccessToken: + request = self._get_jwt_assertion_request(scopes, assertion, **kwargs) + return self._run_pipeline(request, **kwargs) + + def obtain_token_by_refresh_token(self, scopes: Iterable[str], refresh_token: str, **kwargs: Any) -> AccessToken: + request = self._get_refresh_token_request(scopes, refresh_token, **kwargs) + return self._run_pipeline(request, **kwargs) + + def obtain_token_on_behalf_of( + self, + scopes: Iterable[str], + client_credential: Union[str, AadClientCertificate], + user_assertion: str, + **kwargs: Any + ) -> AccessToken: + # no need for an implementation, non-async OnBehalfOfCredential acquires tokens through MSAL + raise NotImplementedError() + + def _build_pipeline(self, **kwargs: Any) -> Pipeline: + return build_pipeline(**kwargs) + + def _run_pipeline(self, request: HttpRequest, **kwargs: Any) -> AccessToken: + # remove tenant_id and claims kwarg that could have been passed from credential's get_token method + # tenant_id is already part of `request` at this point + kwargs.pop("tenant_id", None) + kwargs.pop("claims", None) + enable_cae = kwargs.pop("enable_cae", False) + now = int(time.time()) + response = self._pipeline.run(request, retry_on_methods=self._POST, **kwargs) + return self._process_response(response, now, enable_cae=enable_cae, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/aad_client_base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/aad_client_base.py new file mode 100644 index 0000000000000000000000000000000000000000..16182293050c0268a9f0135aaa083d796fe70532 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/aad_client_base.py @@ -0,0 +1,376 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import base64 +import json +import time +from uuid import uuid4 +from typing import TYPE_CHECKING, List, Any, Iterable, Optional, Union, Dict + +from msal import TokenCache + +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.policies import ContentDecodePolicy +from azure.core.pipeline.transport import HttpRequest +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError +from .utils import get_default_authority, normalize_authority, resolve_tenant +from .aadclient_certificate import AadClientCertificate +from .._persistent_cache import _load_persistent_cache + + +if TYPE_CHECKING: + from azure.core.pipeline import AsyncPipeline, Pipeline + from azure.core.pipeline.policies import AsyncHTTPPolicy, HTTPPolicy, SansIOHTTPPolicy + from azure.core.pipeline.transport import AsyncHttpTransport, HttpTransport + + PipelineType = Union[AsyncPipeline, Pipeline] + PolicyType = Union[AsyncHTTPPolicy, HTTPPolicy, SansIOHTTPPolicy] + TransportType = Union[AsyncHttpTransport, HttpTransport] + +JWT_BEARER_ASSERTION = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" + + +class AadClientBase(abc.ABC): + _POST = ["POST"] + + def __init__( + self, + tenant_id: str, + client_id: str, + authority: Optional[str] = None, + cache: Optional[TokenCache] = None, + cae_cache: Optional[TokenCache] = None, + *, + additionally_allowed_tenants: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + self._authority = normalize_authority(authority) if authority else get_default_authority() + + self._tenant_id = tenant_id + self._client_id = client_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._pipeline = self._build_pipeline(**kwargs) + + self._cache = cache + self._cae_cache = cae_cache + self._cache_options = kwargs.pop("cache_persistence_options", None) + + def _get_cache(self, **kwargs: Any) -> TokenCache: + cache = self._cae_cache if kwargs.get("enable_cae") else self._cache + if not cache: + cache = self._initialize_cache(is_cae=bool(kwargs.get("enable_cae"))) + return cache + + def _initialize_cache(self, is_cae: bool = False) -> TokenCache: + if self._cache_options: + if is_cae: + self._cae_cache = _load_persistent_cache(self._cache_options, is_cae) + else: + self._cache = _load_persistent_cache(self._cache_options, is_cae) + else: + if is_cae: + self._cae_cache = TokenCache() + else: + self._cache = TokenCache() + return self._cae_cache if is_cae else self._cache + + def get_cached_access_token(self, scopes: Iterable[str], **kwargs: Any) -> Optional[AccessToken]: + tenant = resolve_tenant( + self._tenant_id, additionally_allowed_tenants=self._additionally_allowed_tenants, **kwargs + ) + + cache = self._get_cache(**kwargs) + tokens = cache.find( + TokenCache.CredentialType.ACCESS_TOKEN, + target=list(scopes), + query={"client_id": self._client_id, "realm": tenant}, + ) + for token in tokens: + expires_on = int(token["expires_on"]) + if expires_on > int(time.time()): + return AccessToken(token["secret"], expires_on) + return None + + def get_cached_refresh_tokens(self, scopes: Iterable[str], **kwargs) -> List[Dict]: + # Assumes all cached refresh tokens belong to the same user + cache = self._get_cache(**kwargs) + return cache.find(TokenCache.CredentialType.REFRESH_TOKEN, target=list(scopes)) + + @abc.abstractmethod + def obtain_token_by_authorization_code(self, scopes, code, redirect_uri, client_secret=None, **kwargs): + pass + + @abc.abstractmethod + def obtain_token_by_jwt_assertion(self, scopes, assertion, **kwargs): + pass + + @abc.abstractmethod + def obtain_token_by_client_certificate(self, scopes, certificate, **kwargs): + pass + + @abc.abstractmethod + def obtain_token_by_client_secret(self, scopes, secret, **kwargs): + pass + + @abc.abstractmethod + def obtain_token_by_refresh_token(self, scopes, refresh_token, **kwargs): + pass + + @abc.abstractmethod + def obtain_token_on_behalf_of(self, scopes, client_credential, user_assertion, **kwargs): + pass + + @abc.abstractmethod + def _build_pipeline(self, **kwargs): + pass + + def _process_response(self, response: PipelineResponse, request_time: int, **kwargs) -> AccessToken: + content = response.context.get( + ContentDecodePolicy.CONTEXT_NAME + ) or ContentDecodePolicy.deserialize_from_http_generics(response.http_response) + + cache = self._get_cache(**kwargs) + if response.http_request.body.get("grant_type") == "refresh_token": + if content.get("error") == "invalid_grant": + # the request's refresh token is invalid -> evict it from the cache + cache_entries = cache.find( + TokenCache.CredentialType.REFRESH_TOKEN, + query={"secret": response.http_request.body["refresh_token"]}, + ) + for invalid_token in cache_entries: + cache.remove_rt(invalid_token) + if "refresh_token" in content: + # Microsoft Entra ID returned a new refresh token -> update the cache entry + cache_entries = cache.find( + TokenCache.CredentialType.REFRESH_TOKEN, + query={"secret": response.http_request.body["refresh_token"]}, + ) + # If the old token is in multiple cache entries, the cache is in a state we don't + # expect or know how to reason about, so we update nothing. + if len(cache_entries) == 1: + cache.update_rt(cache_entries[0], content["refresh_token"]) + del content["refresh_token"] # prevent caching a redundant entry + + _raise_for_error(response, content) + + if "expires_on" in content: + expires_on = int(content["expires_on"]) + elif "expires_in" in content: + expires_on = request_time + int(content["expires_in"]) + else: + _scrub_secrets(content) + raise ClientAuthenticationError(message="Unexpected response from Microsoft Entra ID: {}".format(content)) + + token = AccessToken(content["access_token"], expires_on) + + # caching is the final step because 'add' mutates 'content' + cache.add( + event={ + "client_id": self._client_id, + "response": content, + "scope": response.http_request.body["scope"].split(), + "token_endpoint": response.http_request.url, + }, + now=request_time, + ) + + return token + + def _get_auth_code_request( + self, scopes: Iterable[str], code: str, redirect_uri: str, client_secret: Optional[str] = None, **kwargs: Any + ) -> HttpRequest: + data = { + "client_id": self._client_id, + "code": code, + "grant_type": "authorization_code", + "redirect_uri": redirect_uri, + "scope": " ".join(scopes), + } + + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + if client_secret: + data["client_secret"] = client_secret + + request = self._post(data, **kwargs) + return request + + def _get_jwt_assertion_request(self, scopes: Iterable[str], assertion: str, **kwargs: Any) -> HttpRequest: + data = { + "client_assertion": assertion, + "client_assertion_type": JWT_BEARER_ASSERTION, + "client_id": self._client_id, + "grant_type": "client_credentials", + "scope": " ".join(scopes), + } + + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + + request = self._post(data, **kwargs) + return request + + def _get_client_certificate_assertion(self, certificate: AadClientCertificate, **kwargs: Any) -> str: + now = int(time.time()) + header = json.dumps({"typ": "JWT", "alg": "RS256", "x5t": certificate.thumbprint}).encode("utf-8") + payload = json.dumps( + { + "jti": str(uuid4()), + "aud": self._get_token_url(**kwargs), + "iss": self._client_id, + "sub": self._client_id, + "nbf": now, + "exp": now + (60 * 30), + } + ).encode("utf-8") + jws = base64.urlsafe_b64encode(header) + b"." + base64.urlsafe_b64encode(payload) + signature = certificate.sign(jws) + jwt_bytes = jws + b"." + base64.urlsafe_b64encode(signature) + return jwt_bytes.decode("utf-8") + + def _get_client_certificate_request( + self, scopes: Iterable[str], certificate: AadClientCertificate, **kwargs: Any + ) -> HttpRequest: + assertion = self._get_client_certificate_assertion(certificate, **kwargs) + return self._get_jwt_assertion_request(scopes, assertion, **kwargs) + + def _get_client_secret_request(self, scopes: Iterable[str], secret: str, **kwargs: Any) -> HttpRequest: + data = { + "client_id": self._client_id, + "client_secret": secret, + "grant_type": "client_credentials", + "scope": " ".join(scopes), + } + + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + + request = self._post(data, **kwargs) + return request + + def _get_on_behalf_of_request( + self, + scopes: Iterable[str], + client_credential: Union[str, AadClientCertificate], + user_assertion: str, + **kwargs: Any + ) -> HttpRequest: + data = { + "assertion": user_assertion, + "client_id": self._client_id, + "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", + "requested_token_use": "on_behalf_of", + "scope": " ".join(scopes), + } + + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + + if isinstance(client_credential, AadClientCertificate): + data["client_assertion"] = self._get_client_certificate_assertion(client_credential) + data["client_assertion_type"] = JWT_BEARER_ASSERTION + else: + data["client_secret"] = client_credential + + request = self._post(data, **kwargs) + return request + + def _get_refresh_token_request(self, scopes: Iterable[str], refresh_token: str, **kwargs: Any) -> HttpRequest: + data = { + "grant_type": "refresh_token", + "refresh_token": refresh_token, + "scope": " ".join(scopes), + "client_id": self._client_id, + "client_info": 1, # request Microsoft Entra ID include home_account_id in its response + } + + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + + request = self._post(data, **kwargs) + return request + + def _get_refresh_token_on_behalf_of_request( + self, + scopes: Iterable[str], + client_credential: Union[str, AadClientCertificate], + refresh_token: str, + **kwargs: Any + ) -> HttpRequest: + data = { + "grant_type": "refresh_token", + "refresh_token": refresh_token, + "scope": " ".join(scopes), + "client_id": self._client_id, + "client_info": 1, # request Microsoft Entra ID include home_account_id in its response + } + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + + if isinstance(client_credential, AadClientCertificate): + data["client_assertion"] = self._get_client_certificate_assertion(client_credential) + data["client_assertion_type"] = JWT_BEARER_ASSERTION + else: + data["client_secret"] = client_credential + request = self._post(data, **kwargs) + return request + + def _get_token_url(self, **kwargs: Any) -> str: + tenant = resolve_tenant( + self._tenant_id, additionally_allowed_tenants=self._additionally_allowed_tenants, **kwargs + ) + return "/".join((self._authority, tenant, "oauth2/v2.0/token")) + + def _post(self, data: Dict, **kwargs: Any) -> HttpRequest: + url = self._get_token_url(**kwargs) + return HttpRequest("POST", url, data=data, headers={"Content-Type": "application/x-www-form-urlencoded"}) + + +def _merge_claims_challenge_and_capabilities(capabilities, claims_challenge): + # Represent capabilities as {"access_token": {"xms_cc": {"values": capabilities}}} + # and then merge/add it into incoming claims + if not capabilities: + return claims_challenge + claims_dict = json.loads(claims_challenge) if claims_challenge else {} + for key in ["access_token"]: + claims_dict.setdefault(key, {}).update(xms_cc={"values": capabilities}) + return json.dumps(claims_dict) + + +def _scrub_secrets(response: Dict) -> None: + for secret in ("access_token", "refresh_token"): + if secret in response: + response[secret] = "***" + + +def _raise_for_error(response: PipelineResponse, content: Dict) -> None: + if "error" not in content: + return + + _scrub_secrets(content) + if "error_description" in content: + message = "Microsoft Entra ID error '({}) {}'".format(content["error"], content["error_description"]) + else: + message = "Microsoft Entra ID error '{}'".format(content) + raise ClientAuthenticationError(message=message, response=response.http_response) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/aadclient_certificate.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/aadclient_certificate.py new file mode 100644 index 0000000000000000000000000000000000000000..e6371c8f2d56667df293f407fea88320ab604623 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/aadclient_certificate.py @@ -0,0 +1,46 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import base64 +from typing import Optional +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import padding +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey +from cryptography.hazmat.backends import default_backend + + +class AadClientCertificate: + """Wraps 'cryptography' to provide the crypto operations AadClient requires for certificate authentication. + + :param bytes pem_bytes: bytes of a a PEM-encoded certificate including the (RSA) private key + :param bytes password: (optional) the certificate's password + """ + + def __init__(self, pem_bytes: bytes, password: Optional[bytes] = None) -> None: + private_key = serialization.load_pem_private_key(pem_bytes, password=password, backend=default_backend()) + if not isinstance(private_key, RSAPrivateKey): + raise ValueError("The certificate must have an RSA private key because RS256 is used for signing") + self._private_key = private_key + + cert = x509.load_pem_x509_certificate(pem_bytes, default_backend()) + fingerprint = cert.fingerprint(hashes.SHA1()) # nosec + self._thumbprint = base64.urlsafe_b64encode(fingerprint).decode("utf-8") + + @property + def thumbprint(self) -> str: + """The certificate's SHA1 thumbprint as a base64url-encoded string. + + :rtype: str + """ + return self._thumbprint + + def sign(self, plaintext: bytes) -> bytes: + """Sign bytes using RS256. + + :param bytes plaintext: Bytes to sign. + :return: The signature. + :rtype: bytes + """ + return self._private_key.sign(plaintext, padding.PKCS1v15(), hashes.SHA256()) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/auth_code_redirect_handler.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/auth_code_redirect_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..7883d19dfabd706b08c26d04bbc9f0b996846966 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/auth_code_redirect_handler.py @@ -0,0 +1,62 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Mapping + +from http.server import HTTPServer, BaseHTTPRequestHandler +from urllib.parse import parse_qs + + +class AuthCodeRedirectHandler(BaseHTTPRequestHandler): + """HTTP request handler to capture the authentication server's response. + Mostly from the Azure CLI: https://github.com/Azure/azure-cli/blob/dev/src/azure-cli-core/azure/cli/core/_profile.py + """ + + def do_GET(self): + if self.path.endswith("/favicon.ico"): # deal with legacy IE + self.send_response(204) + return + + query = self.path.split("?", 1)[-1] + parsed = parse_qs(query, keep_blank_values=True) + self.server.query_params = {k: v[0] if isinstance(v, list) and len(v) == 1 else v for k, v in parsed.items()} + + self.send_response(200) + self.send_header("Content-Type", "text/html") + self.end_headers() + + self.wfile.write(b"Authentication complete. You can close this window.") + + def log_message(self, format, *args): # pylint: disable=redefined-builtin,unused-argument + pass # this prevents server dumping messages to stdout + + +class AuthCodeRedirectServer(HTTPServer): + """HTTP server that listens for the redirect request following an authorization code authentication""" + + query_params = {} # type: Mapping[str, Any] + + def __init__(self, hostname, port, timeout): + # type: (str, int, int) -> None + HTTPServer.__init__(self, (hostname, port), AuthCodeRedirectHandler) + self.timeout = timeout + + def wait_for_redirect(self): + # type: () -> Mapping[str, Any] + while not self.query_params: + try: + self.handle_request() + except (IOError, ValueError): + # socket has been closed, probably by handle_timeout + break + + # ensure the underlying socket is closed (a no-op when the socket is already closed) + self.server_close() + + # if we timed out, this returns an empty dict + return self.query_params + + def handle_timeout(self): + """Break the request-handling loop by tearing down the server""" + self.server_close() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/client_credential_base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/client_credential_base.py new file mode 100644 index 0000000000000000000000000000000000000000..81579e3bdec6ae92f5052706351e421cc07c7e0d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/client_credential_base.py @@ -0,0 +1,45 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import time +from typing import Any, Optional, Dict + +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError +from .get_token_mixin import GetTokenMixin + +from . import wrap_exceptions +from .msal_credentials import MsalCredential + + +def _get_known_kwargs(kwargs: Dict[str, Any]): + # Remove kwargs not expected by MSAL. These aren't typically passed by users, but this is a precaution. + known_kwargs = {"force_refresh", "authority", "correlation_id", "data"} + return {k: v for k, v in kwargs.items() if k in known_kwargs} + + +class ClientCredentialBase(MsalCredential, GetTokenMixin): + """Base class for credentials authenticating a service principal with a certificate or secret""" + + @wrap_exceptions + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + app = self._get_app(**kwargs) + request_time = int(time.time()) + result = app.acquire_token_silent_with_error( + list(scopes), account=None, claims_challenge=kwargs.pop("claims", None), **_get_known_kwargs(kwargs) + ) + if result and "access_token" in result and "expires_in" in result: + return AccessToken(result["access_token"], request_time + int(result["expires_in"])) + return None + + @wrap_exceptions + def _request_token(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + app = self._get_app(**kwargs) + request_time = int(time.time()) + result = app.acquire_token_for_client(list(scopes), claims_challenge=kwargs.pop("claims", None)) + if "access_token" not in result: + message = "Authentication failed: {}".format(result.get("error_description") or result.get("error")) + raise ClientAuthenticationError(message=message) + + return AccessToken(result["access_token"], request_time + int(result["expires_in"])) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/decorators.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..22d443ac54f2008cfa86d8d8bce91d8c1464552d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/decorators.py @@ -0,0 +1,86 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import logging +import json +import base64 + +from azure.core.exceptions import ClientAuthenticationError + +from .utils import within_credential_chain + + +_LOGGER = logging.getLogger(__name__) + + +def log_get_token(class_name): + """Adds logging around get_token calls. + + :param str class_name: required for the sake of Python 2.7, which lacks an easy way to get the credential's class + name from the decorated function + :return: decorator function + :rtype: callable + """ + + def decorator(fn): + qualified_name = class_name + ".get_token" + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + try: + token = fn(*args, **kwargs) + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.INFO, "%s succeeded", qualified_name + ) + if _LOGGER.isEnabledFor(logging.DEBUG): + try: + base64_meta_data = token.token.split(".")[1].encode("utf-8") + b"==" + json_bytes = base64.decodebytes(base64_meta_data) + json_string = json_bytes.decode("utf-8") + json_dict = json.loads(json_string) + upn = json_dict.get("upn", "unavailableUpn") + log_string = ( + "[Authenticated account] Client ID: {}. Tenant ID: {}. User Principal Name: {}. " + "Object ID (user): {}".format(json_dict["appid"], json_dict["tid"], upn, json_dict["oid"]) + ) + _LOGGER.debug(log_string) + except Exception: # pylint: disable=broad-except + _LOGGER.debug("Fail to log the account information") + return token + except Exception as ex: # pylint: disable=broad-except + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.WARNING, + "%s failed: %s", + qualified_name, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise + + return wrapper + + return decorator + + +def wrap_exceptions(fn): + """Prevents leaking exceptions defined outside azure-core by raising ClientAuthenticationError from them. + + :param fn: The function to wrap. + :type fn: ~typing.Callable + :return: The wrapped function. + :rtype: callable + """ + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + try: + return fn(*args, **kwargs) + except ClientAuthenticationError: + raise + except Exception as ex: # pylint:disable=broad-except + auth_error = ClientAuthenticationError(message="Authentication failed: {}".format(ex)) + raise auth_error from ex + + return wrapper diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/get_token_mixin.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/get_token_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..a3dc76ce507be3840e54883b4e20ff81668cfe35 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/get_token_mixin.py @@ -0,0 +1,108 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import logging +import time +from typing import Any, Optional + +from azure.core.credentials import AccessToken +from .utils import within_credential_chain +from .._constants import DEFAULT_REFRESH_OFFSET, DEFAULT_TOKEN_REFRESH_RETRY_DELAY + +_LOGGER = logging.getLogger(__name__) + + +class GetTokenMixin(abc.ABC): + def __init__(self, *args: Any, **kwargs: Any) -> None: + self._last_request_time = 0 + + # https://github.com/python/mypy/issues/5887 + super(GetTokenMixin, self).__init__(*args, **kwargs) # type: ignore + + @abc.abstractmethod + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + """Attempt to acquire an access token from a cache or by redeeming a refresh token. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + + :return: An access token with the desired scopes if successful; otherwise, None. + :rtype: ~azure.core.credentials.AccessToken or None + """ + + @abc.abstractmethod + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + """Request an access token from the STS. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + """ + + def _should_refresh(self, token: AccessToken) -> bool: + now = int(time.time()) + if token.expires_on - now > DEFAULT_REFRESH_OFFSET: + return False + if now - self._last_request_time < DEFAULT_TOKEN_REFRESH_RETRY_DELAY: + return False + return True + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + if not scopes: + raise ValueError('"get_token" requires at least one scope') + + try: + token = self._acquire_token_silently(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + if not token: + self._last_request_time = int(time.time()) + token = self._request_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + elif self._should_refresh(token): + try: + self._last_request_time = int(time.time()) + token = self._request_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + except Exception: # pylint:disable=broad-except + pass + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.INFO, + "%s.get_token succeeded", + self.__class__.__name__, + ) + return token + + except Exception as ex: + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.WARNING, + "%s.get_token failed: %s", + self.__class__.__name__, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/interactive.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/interactive.py new file mode 100644 index 0000000000000000000000000000000000000000..85b33c8c551ae3ca5200d5dd9343f1710c2c3581 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/interactive.py @@ -0,0 +1,231 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Base class for credentials using MSAL for interactive user authentication""" + +import abc +import base64 +import json +import logging +import time +from typing import Any, Optional +from urllib.parse import urlparse + +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError + +from .msal_credentials import MsalCredential +from .._auth_record import AuthenticationRecord +from .._constants import KnownAuthorities +from .._exceptions import AuthenticationRequiredError, CredentialUnavailableError +from .._internal import wrap_exceptions + +ABC = abc.ABC + +_LOGGER = logging.getLogger(__name__) + +_DEFAULT_AUTHENTICATE_SCOPES = { + "https://" + KnownAuthorities.AZURE_CHINA: ("https://management.core.chinacloudapi.cn//.default",), + "https://" + KnownAuthorities.AZURE_GERMANY: ("https://management.core.cloudapi.de//.default",), + "https://" + KnownAuthorities.AZURE_GOVERNMENT: ("https://management.core.usgovcloudapi.net//.default",), + "https://" + KnownAuthorities.AZURE_PUBLIC_CLOUD: ("https://management.core.windows.net//.default",), +} + + +def _decode_client_info(raw) -> str: + """Decode client info. Taken from msal.oauth2cli.oidc. + + :param str raw: base64-encoded client info + :return: decoded client info + :rtype: str + """ + + raw += "=" * (-len(raw) % 4) + raw = str(raw) # On Python 2.7, argument of urlsafe_b64decode must be str, not unicode. + return base64.urlsafe_b64decode(raw).decode("utf-8") + + +def _build_auth_record(response): + """Build an AuthenticationRecord from the result of an MSAL ClientApplication token request. + + :param response: The result of a token request + :type response: dict[str, typing.Any] + :return: An AuthenticationRecord + :rtype: ~azure.identity.AuthenticationRecord + :raises ~azure.core.exceptions.ClientAuthenticationError: If the response doesn't contain expected data + """ + + try: + id_token = response["id_token_claims"] + + if "client_info" in response: + client_info = json.loads(_decode_client_info(response["client_info"])) + home_account_id = "{uid}.{utid}".format(**client_info) + else: + # MSAL uses the subject claim as home_account_id when the STS doesn't provide client_info + home_account_id = id_token["sub"] + + # "iss" is the URL of the issuing tenant e.g. https://authority/tenant + issuer = urlparse(id_token["iss"]) + + # tenant which issued the token, not necessarily user's home tenant + tenant_id = id_token.get("tid") or issuer.path.strip("/") + + # Microsoft Entra ID returns "preferred_username", ADFS returns "upn" + username = id_token.get("preferred_username") or id_token["upn"] + + return AuthenticationRecord( + authority=issuer.netloc, + client_id=id_token["aud"], + home_account_id=home_account_id, + tenant_id=tenant_id, + username=username, + ) + except (KeyError, ValueError) as ex: + auth_error = ClientAuthenticationError( + message="Failed to build AuthenticationRecord from unexpected identity token" + ) + raise auth_error from ex + + +class InteractiveCredential(MsalCredential, ABC): + def __init__( + self, + *, + authentication_record: Optional[AuthenticationRecord] = None, + disable_automatic_authentication: bool = False, + **kwargs: Any + ) -> None: + self._disable_automatic_authentication = disable_automatic_authentication + self._auth_record = authentication_record + if self._auth_record: + kwargs.pop("client_id", None) # authentication_record overrides client_id argument + tenant_id = kwargs.pop("tenant_id", None) or self._auth_record.tenant_id + super(InteractiveCredential, self).__init__( + client_id=self._auth_record.client_id, + authority=self._auth_record.authority, + tenant_id=tenant_id, + **kwargs + ) + else: + super(InteractiveCredential, self).__init__(**kwargs) + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + :raises AuthenticationRequiredError: user interaction is necessary to acquire a token, and the credential is + configured not to begin this automatically. Call :func:`authenticate` to begin interactive authentication. + """ + if not scopes: + message = "'get_token' requires at least one scope" + _LOGGER.warning("%s.get_token failed: %s", self.__class__.__name__, message) + raise ValueError(message) + + allow_prompt = kwargs.pop("_allow_prompt", not self._disable_automatic_authentication) + try: + token = self._acquire_token_silent(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + _LOGGER.info("%s.get_token succeeded", self.__class__.__name__) + return token + except Exception as ex: # pylint:disable=broad-except + if not (isinstance(ex, AuthenticationRequiredError) and allow_prompt): + _LOGGER.warning( + "%s.get_token failed: %s", + self.__class__.__name__, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise + + # silent authentication failed -> authenticate interactively + now = int(time.time()) + + try: + result = self._request_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + if "access_token" not in result: + message = "Authentication failed: {}".format(result.get("error_description") or result.get("error")) + response = self._client.get_error_response(result) + raise ClientAuthenticationError(message=message, response=response) + + # this may be the first authentication, or the user may have authenticated a different identity + self._auth_record = _build_auth_record(result) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.warning( + "%s.get_token failed: %s", + self.__class__.__name__, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise + + _LOGGER.info("%s.get_token succeeded", self.__class__.__name__) + return AccessToken(result["access_token"], now + int(result["expires_in"])) + + def authenticate(self, **kwargs: Any) -> AuthenticationRecord: + """Interactively authenticate a user. + + :keyword Iterable[str] scopes: scopes to request during authentication, such as those provided by + :func:`AuthenticationRequiredError.scopes`. If provided, successful authentication will cache an access token + for these scopes. + :keyword str claims: additional claims required in the token, such as those provided by + :func:`AuthenticationRequiredError.claims` + :rtype: ~azure.identity.AuthenticationRecord + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + + scopes = kwargs.pop("scopes", None) + if not scopes: + if self._authority not in _DEFAULT_AUTHENTICATE_SCOPES: + # the credential is configured to use a cloud whose ARM scope we can't determine + raise CredentialUnavailableError( + message="Authenticating in this environment requires a value for the 'scopes' keyword argument." + ) + + scopes = _DEFAULT_AUTHENTICATE_SCOPES[self._authority] + + _ = self.get_token(*scopes, _allow_prompt=True, **kwargs) + return self._auth_record # type: ignore + + @wrap_exceptions + def _acquire_token_silent(self, *scopes: str, **kwargs: Any) -> AccessToken: + result = None + claims = kwargs.get("claims") + if self._auth_record: + app = self._get_app(**kwargs) + for account in app.get_accounts(username=self._auth_record.username): + if account.get("home_account_id") != self._auth_record.home_account_id: + continue + + now = int(time.time()) + result = app.acquire_token_silent_with_error(list(scopes), account=account, claims_challenge=claims) + if result and "access_token" in result and "expires_in" in result: + return AccessToken(result["access_token"], now + int(result["expires_in"])) + + # if we get this far, result is either None or the content of a Microsoft Entra ID error response + if result: + response = self._client.get_error_response(result) + raise AuthenticationRequiredError(scopes, claims=claims, response=response) + raise AuthenticationRequiredError(scopes, claims=claims) + + @abc.abstractmethod + def _request_token(self, *scopes, **kwargs): + pass diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/linux_vscode_adapter.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/linux_vscode_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..d0be19f13133afda0ed0aba3ebb423a5d2229005 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/linux_vscode_adapter.py @@ -0,0 +1,100 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import json +import logging +import ctypes as ct +from .._constants import VSCODE_CREDENTIALS_SECTION + +_LOGGER = logging.getLogger(__name__) + + +def _c_str(string): + return ct.c_char_p(string.encode("utf-8")) + + +class _SECRET_SCHEMA_ATTRIBUTE(ct.Structure): + _fields_ = [ + ("name", ct.c_char_p), + ("type", ct.c_uint), + ] + + +class _SECRET_SCHEMA(ct.Structure): + _fields_ = [ + ("name", ct.c_char_p), + ("flags", ct.c_uint), + ("attributes", _SECRET_SCHEMA_ATTRIBUTE * 2), + ] + + +_PSECRET_SCHEMA = ct.POINTER(_SECRET_SCHEMA) + + +try: + _libsecret = ct.cdll.LoadLibrary("libsecret-1.so.0") + _libsecret.secret_password_lookup_sync.argtypes = [ + ct.c_void_p, + ct.c_void_p, + ct.c_void_p, + ct.c_char_p, + ct.c_char_p, + ct.c_char_p, + ct.c_char_p, + ct.c_void_p, + ] + _libsecret.secret_password_lookup_sync.restype = ct.c_char_p + _libsecret.secret_password_free.argtypes = [ct.c_char_p] +except OSError: + _libsecret = None # type: ignore + + +def _get_refresh_token(service_name, account_name): + if not _libsecret: + return None + + err = ct.c_int() + attributes = [_SECRET_SCHEMA_ATTRIBUTE(_c_str("service"), 0), _SECRET_SCHEMA_ATTRIBUTE(_c_str("account"), 0)] + pattributes = (_SECRET_SCHEMA_ATTRIBUTE * 2)(*attributes) + schema = _SECRET_SCHEMA() + pschema = _PSECRET_SCHEMA(schema) + ct.memset(pschema, 0, ct.sizeof(schema)) + schema.name = _c_str("org.freedesktop.Secret.Generic") # pylint: disable=attribute-defined-outside-init + schema.flags = 2 # pylint: disable=attribute-defined-outside-init + schema.attributes = pattributes # pylint: disable=attribute-defined-outside-init + p_str = _libsecret.secret_password_lookup_sync( + pschema, + None, + ct.byref(err), + _c_str("service"), + _c_str(service_name), + _c_str("account"), + _c_str(account_name), + None, + ) + if err.value == 0 and p_str: + return p_str.decode("utf-8") + + return None + + +def get_user_settings(): + try: + path = os.path.join(os.environ["HOME"], ".config", "Code", "User", "settings.json") + with open(path, encoding="utf-8") as file: + return json.load(file) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.debug('Exception reading VS Code user settings: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG)) + return {} + + +def get_refresh_token(cloud_name): + try: + return _get_refresh_token(VSCODE_CREDENTIALS_SECTION, cloud_name) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.debug( + 'Exception retrieving VS Code credentials: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG) + ) + return None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/macos_vscode_adapter.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/macos_vscode_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..96643cd10d5ea33685c64649d343d6ea94ba6df9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/macos_vscode_adapter.py @@ -0,0 +1,34 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import json +import logging +from msal_extensions.osx import Keychain, KeychainError +from .._constants import VSCODE_CREDENTIALS_SECTION + +_LOGGER = logging.getLogger(__name__) + + +def get_user_settings(): + try: + path = os.path.join(os.environ["HOME"], "Library", "Application Support", "Code", "User", "settings.json") + with open(path, encoding="utf-8") as file: + return json.load(file) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.debug('Exception reading VS Code user settings: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG)) + return {} + + +def get_refresh_token(cloud_name): + try: + key_chain = Keychain() + return key_chain.get_generic_password(VSCODE_CREDENTIALS_SECTION, cloud_name) + except KeychainError: + return None + except Exception as ex: # pylint:disable=broad-except + _LOGGER.debug( + 'Exception retrieving VS Code credentials: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG) + ) + return None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/managed_identity_base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/managed_identity_base.py new file mode 100644 index 0000000000000000000000000000000000000000..554122530f8379b2929a33ef14519c1cba0e05e6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/managed_identity_base.py @@ -0,0 +1,55 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +from typing import cast, Any, Optional + +from azure.core.credentials import AccessToken +from .. import CredentialUnavailableError +from .._internal.managed_identity_client import ManagedIdentityClient +from .._internal.get_token_mixin import GetTokenMixin + + +class ManagedIdentityBase(GetTokenMixin): + """Base class for internal credentials using ManagedIdentityClient""" + + def __init__(self, **kwargs: Any) -> None: + super(ManagedIdentityBase, self).__init__() + self._client = self.get_client(**kwargs) + + @abc.abstractmethod + def get_client(self, **kwargs: Any) -> Optional[ManagedIdentityClient]: + pass + + @abc.abstractmethod + def get_unavailable_message(self): + # type: () -> str + pass + + def __enter__(self): + if self._client: + self._client.__enter__() + return self + + def __exit__(self, *args): + if self._client: + self._client.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + if not self._client: + raise CredentialUnavailableError(message=self.get_unavailable_message()) + return super(ManagedIdentityBase, self).get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + # casting because mypy can't determine that these methods are called + # only by get_token, which raises when self._client is None + return cast(ManagedIdentityClient, self._client).get_cached_token(*scopes) + + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + return cast(ManagedIdentityClient, self._client).request_token(*scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/managed_identity_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/managed_identity_client.py new file mode 100644 index 0000000000000000000000000000000000000000..f35a3ff5ecb5e129ca2864ac7b45a1a1a51666b1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/managed_identity_client.py @@ -0,0 +1,117 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import time +from typing import Any, Callable, Dict, Optional + +from msal import TokenCache + +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError, DecodeError +from azure.core.pipeline.policies import ContentDecodePolicy +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest +from .._internal import _scopes_to_resource +from .._internal.pipeline import build_pipeline + + +class ManagedIdentityClientBase(abc.ABC): + # pylint:disable=missing-client-constructor-parameter-credential + def __init__( + self, + request_factory: Callable[[str, dict], HttpRequest], + client_id: Optional[str] = None, + identity_config: Optional[Dict] = None, + **kwargs: Any + ) -> None: + self._cache = kwargs.pop("_cache", None) or TokenCache() + self._content_callback = kwargs.pop("_content_callback", None) + self._identity_config = identity_config or {} + if client_id: + self._identity_config["client_id"] = client_id + self._pipeline = self._build_pipeline(**kwargs) + self._request_factory = request_factory + + def _process_response(self, response: PipelineResponse, request_time: int) -> AccessToken: + content = response.context.get(ContentDecodePolicy.CONTEXT_NAME) + if not content: + try: + content = ContentDecodePolicy.deserialize_from_text( + response.http_response.text(), mime_type="application/json" + ) + except DecodeError as ex: + if response.http_response.content_type.startswith("application/json"): + message = "Failed to deserialize JSON from response" + else: + message = 'Unexpected content type "{}"'.format(response.http_response.content_type) + raise ClientAuthenticationError(message=message, response=response.http_response) from ex + + if not content: + raise ClientAuthenticationError(message="No token received.", response=response.http_response) + + if "access_token" not in content or not ("expires_in" in content or "expires_on" in content): + if content and "access_token" in content: + content["access_token"] = "****" + raise ClientAuthenticationError( + message='Unexpected response "{}"'.format(content), response=response.http_response + ) + + if self._content_callback: + self._content_callback(content) + + expires_on = int(content.get("expires_on") or int(content["expires_in"]) + request_time) + content["expires_on"] = expires_on + + token = AccessToken(content["access_token"], content["expires_on"]) + + # caching is the final step because TokenCache.add mutates its "event" + self._cache.add( + event={"response": content, "scope": [content["resource"]]}, + now=request_time, + ) + + return token + + def get_cached_token(self, *scopes: str) -> Optional[AccessToken]: + resource = _scopes_to_resource(*scopes) + tokens = self._cache.find(TokenCache.CredentialType.ACCESS_TOKEN, target=[resource]) + for token in tokens: + expires_on = int(token["expires_on"]) + if expires_on > time.time(): + return AccessToken(token["secret"], expires_on) + return None + + @abc.abstractmethod + def request_token(self, *scopes, **kwargs): + pass + + @abc.abstractmethod + def _build_pipeline(self, **kwargs): + pass + + +class ManagedIdentityClient(ManagedIdentityClientBase): + def __enter__(self): + self._pipeline.__enter__() + return self + + def __exit__(self, *args): + self._pipeline.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + resource = _scopes_to_resource(*scopes) + request = self._request_factory(resource, self._identity_config) + kwargs.pop("tenant_id", None) + kwargs.pop("claims", None) + request_time = int(time.time()) + response = self._pipeline.run(request, retry_on_methods=[request.method], **kwargs) + token = self._process_response(response, request_time) + return token + + def _build_pipeline(self, **kwargs): + return build_pipeline(**kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/msal_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/msal_client.py new file mode 100644 index 0000000000000000000000000000000000000000..e044f8b7f522d3c64f036de05342d5c2729055b9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/msal_client.py @@ -0,0 +1,133 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import threading +from typing import Any, Dict, Optional, Union + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.pipeline.policies import ContentDecodePolicy +from azure.core.pipeline.transport import ( # pylint:disable=unknown-option-value,no-legacy-azure-core-http-response-import + HttpRequest, + HttpResponse, +) +from azure.core.pipeline import PipelineResponse +from .pipeline import build_pipeline + +RequestData = Union[Dict[str, str], str] +_POST = ["POST"] + + +class MsalResponse: + """Wraps HttpResponse according to msal.oauth2cli.http. + + :param response: The response to wrap. + :type response: ~azure.core.pipeline.transport.HttpResponse + """ + + def __init__(self, response: PipelineResponse) -> None: + self._response = response + + @property + def status_code(self) -> int: + return self._response.http_response.status_code + + @property + def text(self) -> str: + return self._response.http_response.text(encoding="utf-8") + + def raise_for_status(self): + if self.status_code < 400: + return + + if ContentDecodePolicy.CONTEXT_NAME in self._response.context: + content = self._response.context[ContentDecodePolicy.CONTEXT_NAME] + if not content: + message = "Unexpected response from Microsoft Entra ID" + elif "error" in content or "error_description" in content: + message = "Authentication failed: {}".format(content.get("error_description") or content.get("error")) + else: + for secret in ("access_token", "refresh_token"): + if secret in content: + content[secret] = "***" + message = 'Unexpected response from Microsoft Entra ID: "{}"'.format(content) + else: + message = "Unexpected response from Microsoft Entra ID" + + raise ClientAuthenticationError(message=message, response=self._response.http_response) + + +class MsalClient: # pylint:disable=client-accepts-api-version-keyword + """Wraps Pipeline according to msal.oauth2cli.http""" + + def __init__(self, **kwargs: Any) -> None: # pylint:disable=missing-client-constructor-parameter-credential + self._local = threading.local() + self._pipeline = build_pipeline(**kwargs) + + def __enter__(self): + self._pipeline.__enter__() + return self + + def __exit__(self, *args): + self._pipeline.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def post( + self, + url: str, + params: Optional[Dict[str, str]] = None, + data: Optional[RequestData] = None, + headers: Optional[Dict[str, str]] = None, + **kwargs: Any + ) -> MsalResponse: + # pylint:disable=unused-argument + request = HttpRequest("POST", url, headers=headers) + if params: + request.format_parameters(params) + if data: + if isinstance(data, dict): + request.headers["Content-Type"] = "application/x-www-form-urlencoded" + request.set_formdata_body(data) + elif isinstance(data, str): + body_bytes = data.encode("utf-8") + request.set_bytes_body(body_bytes) + else: + raise ValueError('expected "data" to be text or a dict') + + response = self._pipeline.run(request, stream=False, retry_on_methods=_POST) + self._store_auth_error(response) + return MsalResponse(response) + + def get( + self, url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, **kwargs: Any + ) -> MsalResponse: + # pylint:disable=unused-argument + request = HttpRequest("GET", url, headers=headers) + if params: + request.format_parameters(params) + response = self._pipeline.run(request, stream=False) + self._store_auth_error(response) + return MsalResponse(response) + + def get_error_response(self, msal_result: Dict) -> Optional[HttpResponse]: + """Get the HTTP response associated with an MSAL error. + + :param msal_result: The result of an MSAL request. + :type msal_result: dict + :return: The HTTP response associated with the error, if any. + :rtype: ~azure.core.pipeline.transport.HttpResponse or None + """ + error_code, response = getattr(self._local, "error", (None, None)) + if response and error_code == msal_result.get("error"): + return response + return None + + def _store_auth_error(self, response: PipelineResponse) -> None: + if response.http_response.status_code >= 400: + # if the body doesn't contain "error", this isn't an OAuth 2 error, i.e. this isn't a + # response to an auth request, so no credential will want to include it with an exception + content = response.context.get(ContentDecodePolicy.CONTEXT_NAME) + if content and "error" in content: + self._local.error = (content["error"], response.http_response) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/msal_credentials.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/msal_credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..68db6b5fc362198a7b06784bcb0f1bc45dc3bd2e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/msal_credentials.py @@ -0,0 +1,114 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +from typing import Any, List, Union, Dict, Optional + +import msal + +from .msal_client import MsalClient +from .utils import get_default_authority, normalize_authority, resolve_tenant, validate_tenant_id +from .._constants import EnvironmentVariables +from .._persistent_cache import _load_persistent_cache + + +class MsalCredential: # pylint: disable=too-many-instance-attributes + """Base class for credentials wrapping MSAL applications. + + :param str client_id: the principal's client ID + :param client_credential: client credential data for the application + :type client_credential: dict + """ + + def __init__( + self, + client_id: str, + client_credential: Optional[Union[str, Dict]] = None, + *, + additionally_allowed_tenants: Optional[List[str]] = None, + authority: Optional[str] = None, + disable_instance_discovery: Optional[bool] = None, + tenant_id: Optional[str] = None, + enable_support_logging: Optional[bool] = None, + **kwargs + ) -> None: + self._instance_discovery = None if disable_instance_discovery is None else not disable_instance_discovery + self._authority = normalize_authority(authority) if authority else get_default_authority() + self._regional_authority = os.environ.get(EnvironmentVariables.AZURE_REGIONAL_AUTHORITY_NAME) + if self._regional_authority and self._regional_authority.lower() in ["tryautodetect", "true"]: + self._regional_authority = msal.ConfidentialClientApplication.ATTEMPT_REGION_DISCOVERY + self._tenant_id = tenant_id or "organizations" + validate_tenant_id(self._tenant_id) + self._client = MsalClient(**kwargs) + self._client_credential = client_credential + self._client_id = client_id + self._enable_support_logging = enable_support_logging + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + + self._client_applications: Dict[str, msal.ClientApplication] = {} + self._cae_client_applications: Dict[str, msal.ClientApplication] = {} + + self._cache = kwargs.pop("_cache", None) + self._cae_cache = kwargs.pop("_cae_cache", None) + self._cache_options = kwargs.pop("cache_persistence_options", None) + + super(MsalCredential, self).__init__() + + def __enter__(self): + self._client.__enter__() + return self + + def __exit__(self, *args): + self._client.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def _initialize_cache(self, is_cae: bool = False) -> msal.TokenCache: + if self._cache_options: + if is_cae: + self._cae_cache = _load_persistent_cache(self._cache_options, is_cae) + else: + self._cache = _load_persistent_cache(self._cache_options, is_cae) + else: + if is_cae: + self._cae_cache = msal.TokenCache() + else: + self._cache = msal.TokenCache() + + return self._cae_cache if is_cae else self._cache + + def _get_app(self, **kwargs: Any) -> msal.ClientApplication: + tenant_id = resolve_tenant( + self._tenant_id, additionally_allowed_tenants=self._additionally_allowed_tenants, **kwargs + ) + + client_applications_map = self._client_applications + capabilities = None + token_cache = self._cache + + app_class = msal.ConfidentialClientApplication if self._client_credential else msal.PublicClientApplication + + if kwargs.get("enable_cae"): + client_applications_map = self._cae_client_applications + capabilities = ["CP1"] + token_cache = self._cae_cache + + if not token_cache: + token_cache = self._initialize_cache(is_cae=bool(kwargs.get("enable_cae"))) + + if tenant_id not in client_applications_map: + client_applications_map[tenant_id] = app_class( + client_id=self._client_id, + client_credential=self._client_credential, + client_capabilities=capabilities, + authority="{}/{}".format(self._authority, tenant_id), + azure_region=self._regional_authority, + token_cache=token_cache, + http_client=self._client, + instance_discovery=self._instance_discovery, + enable_pii_log=self._enable_support_logging, + ) + + return client_applications_map[tenant_id] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/pipeline.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..de714e49e756005fc097e4d93f93d746e91f0dff --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/pipeline.py @@ -0,0 +1,94 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from azure.core.configuration import Configuration +from azure.core.pipeline import Pipeline +from azure.core.pipeline.policies import ( + ContentDecodePolicy, + CustomHookPolicy, + DistributedTracingPolicy, + HeadersPolicy, + NetworkTraceLoggingPolicy, + ProxyPolicy, + RetryPolicy, + UserAgentPolicy, + HttpLoggingPolicy, +) + + +from .user_agent import USER_AGENT + + +def _get_config(**kwargs) -> Configuration: + """Configuration common to a/sync pipelines. + + :return: A configuration object. + :rtype: ~azure.core.configuration.Configuration + """ + config: Configuration = Configuration(**kwargs) + config.custom_hook_policy = CustomHookPolicy(**kwargs) + config.headers_policy = HeadersPolicy(**kwargs) + config.http_logging_policy = HttpLoggingPolicy(**kwargs) + config.logging_policy = NetworkTraceLoggingPolicy(**kwargs) + config.proxy_policy = ProxyPolicy(**kwargs) + config.user_agent_policy = UserAgentPolicy(base_user_agent=USER_AGENT, **kwargs) + return config + + +def _get_policies(config, _per_retry_policies=None, **kwargs): + policies = [ + config.headers_policy, + config.user_agent_policy, + config.proxy_policy, + ContentDecodePolicy(**kwargs), + config.retry_policy, + ] + + if _per_retry_policies: + policies.extend(_per_retry_policies) + + policies.extend( + [ + config.custom_hook_policy, + config.logging_policy, + DistributedTracingPolicy(**kwargs), + config.http_logging_policy, + ] + ) + + return policies + + +def build_pipeline(transport=None, policies=None, **kwargs): + if not policies: + config = _get_config(**kwargs) + config.retry_policy = RetryPolicy(**kwargs) + policies = _get_policies(config, **kwargs) + if not transport: + from azure.core.pipeline.transport import ( # pylint: disable=non-abstract-transport-import, no-name-in-module + RequestsTransport, + ) + + transport = RequestsTransport(**kwargs) + + return Pipeline(transport, policies=policies) + + +def build_async_pipeline(transport=None, policies=None, **kwargs): + from azure.core.pipeline import AsyncPipeline + + if not policies: + from azure.core.pipeline.policies import AsyncRetryPolicy + + config = _get_config(**kwargs) + config.retry_policy = AsyncRetryPolicy(**kwargs) + policies = _get_policies(config, **kwargs) + if not transport: + from azure.core.pipeline.transport import ( # pylint: disable=non-abstract-transport-import, no-name-in-module + AioHttpTransport, + ) + + transport = AioHttpTransport(**kwargs) + + return AsyncPipeline(transport, policies=policies) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/shared_token_cache.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/shared_token_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..13a52413232f119da935ae7e595f26ddbf8006ff --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/shared_token_cache.py @@ -0,0 +1,269 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import platform +import time +from typing import Any, Iterable, List, Mapping, Optional, cast +from urllib.parse import urlparse +import msal + +from azure.core.credentials import AccessToken +from .. import CredentialUnavailableError +from .._constants import KnownAuthorities +from .._internal import get_default_authority, normalize_authority, wrap_exceptions +from .._persistent_cache import _load_persistent_cache, TokenCachePersistenceOptions +from .._internal import AadClientBase + +ABC = abc.ABC +CacheItem = Mapping[str, str] + +MULTIPLE_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. Multiple accounts +were found in the cache. Use username and tenant id to disambiguate.""" + +MULTIPLE_MATCHING_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. Multiple accounts +matching the specified{}{} were found in the cache.""" + +NO_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.""" + +NO_MATCHING_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. No account +matching the specified{}{} was found in the cache.""" + +NO_TOKEN = """Token acquisition failed for user '{}'. To fix, re-authenticate +through developer tooling supporting Azure single sign on""" + +# build a dictionary {authority: {its known aliases}}, aliases taken from MSAL.NET's KnownMetadataProvider +KNOWN_ALIASES = { + alias: aliases # N.B. aliases includes alias itself + for aliases in ( + frozenset((KnownAuthorities.AZURE_CHINA, "login.partner.microsoftonline.cn")), + frozenset((KnownAuthorities.AZURE_PUBLIC_CLOUD, "login.windows.net", "login.microsoft.com", "sts.windows.net")), + frozenset((KnownAuthorities.AZURE_GOVERNMENT, "login.usgovcloudapi.net")), + ) + for alias in aliases +} + + +def _account_to_string(account): + username = account.get("username") + home_account_id = account.get("home_account_id", "").split(".") + tenant_id = home_account_id[-1] if len(home_account_id) == 2 else "" + return "(username: {}, tenant: {})".format(username, tenant_id) + + +def _filtered_accounts( + accounts: Iterable[CacheItem], username: Optional[str] = None, tenant_id: Optional[str] = None +) -> List[CacheItem]: + """Return accounts matching username and/or tenant_id. + + :param accounts: accounts from the MSAL cache + :type accounts: Iterable[CacheItem] + :param str username: an account's username + :param str tenant_id: an account's tenant ID + :return: accounts matching username and/or tenant_id + :rtype: list[CacheItem] + """ + + filtered_accounts = [] + for account in accounts: + if username and account.get("username") != username: + continue + if tenant_id: + try: + _, tenant = account["home_account_id"].split(".") + if tenant_id != tenant: + continue + except Exception: # pylint:disable=broad-except + continue + filtered_accounts.append(account) + return filtered_accounts + + +class SharedTokenCacheBase(ABC): # pylint: disable=too-many-instance-attributes + def __init__( + self, + username: Optional[str] = None, + *, + authority: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any + ) -> None: # pylint:disable=unused-argument + self._authority = normalize_authority(authority) if authority else get_default_authority() + environment = urlparse(self._authority).netloc + self._environment_aliases = KNOWN_ALIASES.get(environment) or frozenset((environment,)) + self._username = username + self._tenant_id = tenant_id + self._cache = kwargs.pop("_cache", None) + self._cae_cache = kwargs.pop("_cae_cache", None) + self._cache_persistence_options = kwargs.pop("cache_persistence_options", None) + self._client_kwargs = kwargs + self._client_kwargs["tenant_id"] = "organizations" + self._client = cast(AadClientBase, None) + self._client_initialized = False + + def _initialize_client(self) -> None: + if self._client_initialized: + return + + self._client = self._get_auth_client( + authority=self._authority, cache=self._cache, cae_cache=self._cae_cache, **self._client_kwargs + ) + self._client_initialized = True + + def _initialize_cache(self, is_cae: bool = False) -> Optional[msal.TokenCache]: + + # If no cache options were provided, the default cache will be used. This credential accepts the + # user's default cache regardless of whether it's encrypted. It doesn't create a new cache. If the + # default cache exists, the user must have created it earlier. If it's unencrypted, the user must + # have allowed that. + cache_options = self._cache_persistence_options or TokenCachePersistenceOptions(allow_unencrypted_storage=True) + if not self.supported(): + raise CredentialUnavailableError(message="Shared token cache is not supported on this platform.") + + if not self._cache and not is_cae: + try: + self._cache = _load_persistent_cache(cache_options, is_cae) + self._client._cache = self._cache # pylint:disable=protected-access + except Exception: # pylint:disable=broad-except + return None + + if not self._cae_cache and is_cae: + try: + self._cae_cache = _load_persistent_cache(cache_options, is_cae) + self._client._cae_cache = self._cae_cache # pylint:disable=protected-access + except Exception: # pylint:disable=broad-except + return None + + return self._cae_cache if is_cae else self._cache + + @abc.abstractmethod + def _get_auth_client(self, **kwargs) -> AadClientBase: + pass + + def _get_cache_items_for_authority( + self, credential_type: msal.TokenCache.CredentialType, is_cae: bool = False + ) -> List[CacheItem]: + """Return cache items matching this credential's authority or one of its aliases. + + :param credential_type: the type of credential to look for in the cache + :param bool is_cae: whether to look in the CAE cache + :type credential_type: msal.TokenCache.CredentialType + :return: a list of cache items + :rtype: list[CacheItem] + """ + + cache = self._cae_cache if is_cae else self._cache + items = [] + for item in cache.find(credential_type): + environment = item.get("environment") + if environment in self._environment_aliases: + items.append(item) + return items + + def _get_accounts_having_matching_refresh_tokens(self, is_cae: bool = False) -> Iterable[CacheItem]: + """Returns an iterable of cached accounts which have a matching refresh token. + + :param bool is_cae: whether to look in the CAE cache + :return: an iterable of cached accounts + :rtype: Iterable[CacheItem] + """ + + refresh_tokens = self._get_cache_items_for_authority(msal.TokenCache.CredentialType.REFRESH_TOKEN, is_cae) + all_accounts = self._get_cache_items_for_authority(msal.TokenCache.CredentialType.ACCOUNT, is_cae) + + accounts = {} + for refresh_token in refresh_tokens: + home_account_id = refresh_token.get("home_account_id") + if not home_account_id: + continue + for account in all_accounts: + # When the token has no family, msal.net falls back to matching client_id, + # which won't work for the shared cache because we don't know the IDs of + # all contributing apps. It should be unnecessary anyway because the + # apps should all belong to the family. + if home_account_id == account.get("home_account_id") and "family_id" in refresh_token: + accounts[account["home_account_id"]] = account + return accounts.values() + + @wrap_exceptions + def _get_account( + self, username: Optional[str] = None, tenant_id: Optional[str] = None, is_cae: bool = False + ) -> CacheItem: + """Returns exactly one account which has a refresh token and matches username and/or tenant_id. + + :param str username: an account's username + :param str tenant_id: an account's tenant ID + :param bool is_cae: whether to use the CAE cache + :return: an account + :rtype: CacheItem + """ + + accounts = self._get_accounts_having_matching_refresh_tokens(is_cae) + if not accounts: + # cache is empty or contains no refresh token -> user needs to sign in + raise CredentialUnavailableError(message=NO_ACCOUNTS) + + filtered_accounts = _filtered_accounts(accounts, username, tenant_id) + if len(filtered_accounts) == 1: + return filtered_accounts[0] + + # no, or multiple, accounts after filtering -> choose the best error message + cached_accounts = ", ".join(_account_to_string(account) for account in accounts) + if username or tenant_id: + username_string = " username: {}".format(username) if username else "" + tenant_string = " tenant: {}".format(tenant_id) if tenant_id else "" + if filtered_accounts: + message = MULTIPLE_MATCHING_ACCOUNTS.format(username_string, tenant_string) + else: + message = NO_MATCHING_ACCOUNTS.format(username_string, tenant_string) + else: + message = MULTIPLE_ACCOUNTS.format(cached_accounts) + + raise CredentialUnavailableError(message=message) + + def _get_cached_access_token( + self, scopes: Iterable[str], account: CacheItem, is_cae: bool = False + ) -> Optional[AccessToken]: + if "home_account_id" not in account: + return None + + cache = self._cae_cache if is_cae else self._cache + try: + cache_entries = cache.find( + msal.TokenCache.CredentialType.ACCESS_TOKEN, + target=list(scopes), + query={"home_account_id": account["home_account_id"]}, + ) + for token in cache_entries: + expires_on = int(token["expires_on"]) + if expires_on - 300 > int(time.time()): + return AccessToken(token["secret"], expires_on) + except Exception as ex: # pylint:disable=broad-except + message = "Error accessing cached data: {}".format(ex) + raise CredentialUnavailableError(message=message) from ex + + return None + + def _get_refresh_tokens(self, account, is_cae: bool = False) -> List[str]: + if "home_account_id" not in account: + return [] + + cache = self._cae_cache if is_cae else self._cache + try: + cache_entries = cache.find( + msal.TokenCache.CredentialType.REFRESH_TOKEN, query={"home_account_id": account["home_account_id"]} + ) + return [token["secret"] for token in cache_entries if "secret" in token] + except Exception as ex: # pylint:disable=broad-except + message = "Error accessing cached data: {}".format(ex) + raise CredentialUnavailableError(message=message) from ex + + @staticmethod + def supported() -> bool: + """Whether the shared token cache is supported on the current platform. + + :return: True if the shared token cache is supported on the current platform. + :rtype: bool + """ + return platform.system() in {"Darwin", "Linux", "Windows"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/user_agent.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/user_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..f21dfbd945fecace08546200eec17c8dbdf156e7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/user_agent.py @@ -0,0 +1,9 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import platform + +from .._version import VERSION + +USER_AGENT = "azsdk-python-identity/{} Python/{} ({})".format(VERSION, platform.python_version(), platform.platform()) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/utils.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ae2adf66059f4a06546c77d1b91527f07e7f625e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/utils.py @@ -0,0 +1,114 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import logging +from contextvars import ContextVar +from string import ascii_letters, digits +from typing import List, Optional + +from urllib.parse import urlparse + +from azure.core.exceptions import ClientAuthenticationError +from .._constants import EnvironmentVariables, KnownAuthorities + +within_credential_chain = ContextVar("within_credential_chain", default=False) +within_dac = ContextVar("within_dac", default=False) + +_LOGGER = logging.getLogger(__name__) + +VALID_TENANT_ID_CHARACTERS = frozenset(ascii_letters + digits + "-.") +VALID_SCOPE_CHARACTERS = frozenset(ascii_letters + digits + "_-.:/") + + +def normalize_authority(authority: str) -> str: + """Ensure authority uses https, strip trailing spaces and /. + + :param str authority: authority to normalize + :return: normalized authority + :rtype: str + :raises: ValueError if authority is not a valid https URL + """ + + parsed = urlparse(authority) + if not parsed.scheme: + return "https://" + authority.rstrip(" /") + if parsed.scheme != "https": + raise ValueError( + "'{}' is an invalid authority. The value must be a TLS protected (https) URL.".format(authority) + ) + + return authority.rstrip(" /") + + +def get_default_authority() -> str: + authority = os.environ.get(EnvironmentVariables.AZURE_AUTHORITY_HOST, KnownAuthorities.AZURE_PUBLIC_CLOUD) + return normalize_authority(authority) + + +def validate_scope(scope: str) -> None: + """Raise ValueError if scope is empty or contains a character invalid for a scope + + :param str scope: scope to validate + :raises: ValueError if scope is empty or contains a character invalid for a scope. + """ + if not scope or any(c not in VALID_SCOPE_CHARACTERS for c in scope): + raise ValueError( + "An invalid scope was provided. Only alphanumeric characters, '.', '-', '_', ':', and '/' are allowed." + ) + + +def validate_tenant_id(tenant_id: str) -> None: + """Raise ValueError if tenant_id is empty or contains a character invalid for a tenant ID. + + :param str tenant_id: tenant ID to validate + :raises: ValueError if tenant_id is empty or contains a character invalid for a tenant ID. + """ + if not tenant_id or any(c not in VALID_TENANT_ID_CHARACTERS for c in tenant_id): + raise ValueError( + "Invalid tenant ID provided. You can locate your tenant ID by following the instructions here: " + + "https://learn.microsoft.com/partner-center/find-ids-and-domain-names" + ) + + +def resolve_tenant( + default_tenant: str, tenant_id: Optional[str] = None, *, additionally_allowed_tenants: List[str] = [], **_ +) -> str: + """Returns the correct tenant for a token request given a credential's configuration. + + :param str default_tenant: The tenant ID configured on the credential. + :param str tenant_id: The tenant ID requested by the user. + :keyword list[str] additionally_allowed_tenants: The list of additionally allowed tenants. + :return: The tenant ID to use for the token request. + :rtype: str + :raises: ~azure.core.exceptions.ClientAuthenticationError + """ + if tenant_id is None or tenant_id == default_tenant: + return default_tenant + if default_tenant == "adfs" or os.environ.get(EnvironmentVariables.AZURE_IDENTITY_DISABLE_MULTITENANTAUTH): + _LOGGER.info( + "A token was request for a different tenant than was configured on the credential, " + "but the configured value was used since multi tenant authentication has been disabled. " + "Configured tenant ID: %s, Requested tenant ID %s", + default_tenant, + tenant_id, + ) + return default_tenant + if not default_tenant: + return tenant_id + if "*" in additionally_allowed_tenants or tenant_id in additionally_allowed_tenants: + _LOGGER.info( + "A token was requested for a different tenant than was configured on the credential, " + "and the requested tenant ID was used to authenticate. Configured tenant ID: %s, " + "Requested tenant ID %s", + default_tenant, + tenant_id, + ) + return tenant_id + raise ClientAuthenticationError( + message="The current credential is not configured to acquire tokens for tenant {}. " + "To enable acquiring tokens for this tenant add it to the additionally_allowed_tenants " + 'when creating the credential, or add "*" to additionally_allowed_tenants to allow ' + "acquiring tokens for any tenant.".format(tenant_id) + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/win_vscode_adapter.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/win_vscode_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..2cec7ba49e9792b718da1e6bd692452ae0f6b5bd --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_internal/win_vscode_adapter.py @@ -0,0 +1,77 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import json +import logging +import ctypes as ct +from .._constants import VSCODE_CREDENTIALS_SECTION + +try: + import ctypes.wintypes as wt +except (IOError, ValueError): + pass + +_LOGGER = logging.getLogger(__name__) + +SUPPORTED_CREDKEYS = set(("Type", "TargetName", "Persist", "UserName", "Comment", "CredentialBlob")) + +_PBYTE = ct.POINTER(ct.c_byte) + + +class _CREDENTIAL(ct.Structure): + _fields_ = [ + ("Flags", wt.DWORD), + ("Type", wt.DWORD), + ("TargetName", ct.c_wchar_p), + ("Comment", ct.c_wchar_p), + ("LastWritten", wt.FILETIME), + ("CredentialBlobSize", wt.DWORD), + ("CredentialBlob", _PBYTE), + ("Persist", wt.DWORD), + ("AttributeCount", wt.DWORD), + ("Attributes", ct.c_void_p), + ("TargetAlias", ct.c_wchar_p), + ("UserName", ct.c_wchar_p), + ] + + +_PCREDENTIAL = ct.POINTER(_CREDENTIAL) + +_advapi = ct.WinDLL("advapi32") # type: ignore +_advapi.CredReadW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ct.POINTER(_PCREDENTIAL)] +_advapi.CredReadW.restype = wt.BOOL +_advapi.CredFree.argtypes = [_PCREDENTIAL] + + +def _read_credential(service_name, account_name): + target = "{}/{}".format(service_name, account_name) + cred_ptr = _PCREDENTIAL() + if _advapi.CredReadW(target, 1, 0, ct.byref(cred_ptr)): + cred_blob = cred_ptr.contents.CredentialBlob + cred_blob_size = cred_ptr.contents.CredentialBlobSize + cred = "".join(map(chr, cred_blob[:cred_blob_size])) + _advapi.CredFree(cred_ptr) + return cred + return None + + +def get_user_settings(): + try: + path = os.path.join(os.environ["APPDATA"], "Code", "User", "settings.json") + with open(path, encoding="utf-8") as file: + return json.load(file) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.debug('Exception reading VS Code user settings: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG)) + return {} + + +def get_refresh_token(cloud_name): + try: + return _read_credential(VSCODE_CREDENTIALS_SECTION, cloud_name) + except Exception as ex: # pylint: disable=broad-except + _LOGGER.debug( + 'Exception retrieving VS Code credentials: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG) + ) + return None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c6d9763b0263198efad893adf1704c2d6b356434 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/__init__.py @@ -0,0 +1,44 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Credentials for asynchronous Azure SDK clients.""" + +from ._credentials import ( + AuthorizationCodeCredential, + AzureDeveloperCliCredential, + AzureCliCredential, + AzurePowerShellCredential, + CertificateCredential, + ChainedTokenCredential, + ClientSecretCredential, + DefaultAzureCredential, + EnvironmentCredential, + ManagedIdentityCredential, + OnBehalfOfCredential, + SharedTokenCacheCredential, + VisualStudioCodeCredential, + ClientAssertionCredential, + WorkloadIdentityCredential, +) +from ._bearer_token_provider import get_bearer_token_provider + + +__all__ = [ + "AuthorizationCodeCredential", + "AzureDeveloperCliCredential", + "AzureCliCredential", + "AzurePowerShellCredential", + "CertificateCredential", + "ClientSecretCredential", + "DefaultAzureCredential", + "EnvironmentCredential", + "ManagedIdentityCredential", + "OnBehalfOfCredential", + "ChainedTokenCredential", + "SharedTokenCacheCredential", + "VisualStudioCodeCredential", + "ClientAssertionCredential", + "WorkloadIdentityCredential", + "get_bearer_token_provider", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_bearer_token_provider.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_bearer_token_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..bde068e10558d6593d8b58bef756f3b60bca48e4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_bearer_token_provider.py @@ -0,0 +1,47 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Callable, Coroutine, Any + +from azure.core.credentials_async import AsyncTokenCredential +from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy +from azure.core.pipeline import PipelineRequest, PipelineContext +from azure.core.rest import HttpRequest + + +def _make_request() -> PipelineRequest[HttpRequest]: + return PipelineRequest(HttpRequest("CredentialWrapper", "https://fakeurl"), PipelineContext(None)) + + +def get_bearer_token_provider(credential: AsyncTokenCredential, *scopes: str) -> Callable[[], Coroutine[Any, Any, str]]: + """Returns a callable that provides a bearer token. + + It can be used for instance to write code like: + + .. code-block:: python + + from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider + + credential = DefaultAzureCredential() + bearer_token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default") + + + # Usage + request.headers["Authorization"] = "Bearer " + await bearer_token_provider() + + :param credential: The credential used to authenticate the request. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param str scopes: The scopes required for the bearer token. + :rtype: coroutine + :return: A coroutine that returns a bearer token. + """ + + policy = AsyncBearerTokenCredentialPolicy(credential, *scopes) + + async def wrapper() -> str: + request = _make_request() + await policy.on_request(request) + return request.http_request.headers["Authorization"][len("Bearer ") :] + + return wrapper diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..454bf593f1bdc661e566f5f2e896210a4eb59ca1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/__init__.py @@ -0,0 +1,38 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from .authorization_code import AuthorizationCodeCredential +from .azure_powershell import AzurePowerShellCredential +from .chained import ChainedTokenCredential +from .default import DefaultAzureCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from .on_behalf_of import OnBehalfOfCredential +from .certificate import CertificateCredential +from .client_secret import ClientSecretCredential +from .shared_cache import SharedTokenCacheCredential +from .azure_cli import AzureCliCredential +from .azd_cli import AzureDeveloperCliCredential +from .vscode import VisualStudioCodeCredential +from .client_assertion import ClientAssertionCredential +from .workload_identity import WorkloadIdentityCredential + + +__all__ = [ + "AuthorizationCodeCredential", + "AzureCliCredential", + "AzureDeveloperCliCredential", + "AzurePowerShellCredential", + "CertificateCredential", + "ChainedTokenCredential", + "ClientSecretCredential", + "DefaultAzureCredential", + "EnvironmentCredential", + "ManagedIdentityCredential", + "OnBehalfOfCredential", + "SharedTokenCacheCredential", + "VisualStudioCodeCredential", + "ClientAssertionCredential", + "WorkloadIdentityCredential", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/app_service.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/app_service.py new file mode 100644 index 0000000000000000000000000000000000000000..1732802c4033649fedfc05c63dd47d8b6d315ac4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/app_service.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any + +from .._internal.managed_identity_base import AsyncManagedIdentityBase +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._credentials.app_service import _get_client_args + + +class AppServiceCredential(AsyncManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[AsyncManagedIdentityClient]: + client_args = _get_client_args(**kwargs) + if client_args: + return AsyncManagedIdentityClient(**client_args) + return None + + def get_unavailable_message(self) -> str: + return "App Service managed identity configuration not found in environment" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/application.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/application.py new file mode 100644 index 0000000000000000000000000000000000000000..53629eb7c2218f2308c14657d74d8f47b52fd900 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/application.py @@ -0,0 +1,91 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import Optional, Any + +from azure.core.credentials import AccessToken +from .chained import ChainedTokenCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from ..._constants import EnvironmentVariables +from ..._internal import get_default_authority, normalize_authority + +_LOGGER = logging.getLogger(__name__) + + +class AzureApplicationCredential(ChainedTokenCredential): + """A credential for Microsoft Entra applications. + + This credential is designed for applications deployed to Azure (:class:`~azure.identity.aio.DefaultAzureCredential` + is better suited to local development). It authenticates service principals and managed identities. + + For service principal authentication, set these environment variables to identify a principal: + + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its "directory" ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + + And one of these to authenticate that principal: + + - **AZURE_CLIENT_SECRET**: one of the service principal's client secrets + + **or** + + - **AZURE_CLIENT_CERTIFICATE_PATH**: path to a PEM-encoded certificate file including the private key. The + certificate must not be password-protected. + + See `Azure CLI documentation `_ + for more information about creating and managing service principals. + + When this environment configuration is incomplete, the credential will attempt to authenticate a managed identity. + See `Microsoft Entra ID documentation + `_ for an overview + of managed identities. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud, which is the default when no value is given for this keyword argument or + environment variable AZURE_AUTHORITY_HOST. :class:`~azure.identity.AzureAuthorityHosts` defines authorities for + other clouds. Authority configuration applies only to service principal authentication. + :keyword str managed_identity_client_id: The client ID of a user-assigned managed identity. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, a system-assigned identity will be used. + """ + + def __init__( + self, *, authority: Optional[str] = None, managed_identity_client_id: Optional[str] = None, **kwargs: Any + ) -> None: + authority = normalize_authority(authority) if authority else get_default_authority() + managed_identity_client_id = managed_identity_client_id or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + super().__init__( + EnvironmentCredential(authority=authority, **kwargs), + ManagedIdentityCredential(client_id=managed_identity_client_id, **kwargs), + ) + + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Asynchronously request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + token = await self._successful_credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + _LOGGER.info( + "%s acquired a token from %s", self.__class__.__name__, self._successful_credential.__class__.__name__ + ) + return token + + return await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/authorization_code.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/authorization_code.py new file mode 100644 index 0000000000000000000000000000000000000000..d186cd1d52c90261e9f3453d5c9679ae5b250eca --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/authorization_code.py @@ -0,0 +1,120 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any, cast + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessToken +from .._internal import AadClient, AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin + + +class AuthorizationCodeCredential(AsyncContextManager, GetTokenMixin): + """Authenticates by redeeming an authorization code previously obtained from Microsoft Entra ID. + + See `Microsoft Entra ID documentation + `_ for more information + about the authentication flow. + + :param str tenant_id: ID of the application's Microsoft Entra tenant. Also called its "directory" ID. + :param str client_id: The application's client ID + :param str authorization_code: The authorization code from the user's log-in + :param str redirect_uri: The application's redirect URI. Must match the URI used to request the authorization code. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str client_secret: One of the application's client secrets. Required only for web apps and web APIs. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_authorization_code_credential_async] + :end-before: [END create_authorization_code_credential_async] + :language: python + :dedent: 4 + :caption: Create an AuthorizationCodeCredential. + """ + + async def __aenter__(self): + if self._client: + await self._client.__aenter__() + return self + + async def close(self): + """Close the credential's transport session.""" + + if self._client: + await self._client.__aexit__() + + def __init__( + self, + tenant_id: str, + client_id: str, + authorization_code: str, + redirect_uri: str, + *, + client_secret: Optional[str] = None, + **kwargs + ) -> None: + self._authorization_code: Optional[str] = authorization_code + self._client_id = client_id + self._client_secret = client_secret + self._client = kwargs.pop("client", None) or AadClient(tenant_id, client_id, **kwargs) + self._redirect_uri = redirect_uri + super().__init__() + + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + The first time this method is called, the credential will redeem its authorization code. On subsequent calls + the credential will return a cached access token or redeem a refresh token, if it acquired a refresh token upon + redeeming the authorization code. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. Any error response from Microsoft Entra ID is available as the error's + ``response`` attribute. + """ + return await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + if self._authorization_code: + token = await self._client.obtain_token_by_authorization_code( + scopes=scopes, code=self._authorization_code, redirect_uri=self._redirect_uri, **kwargs + ) + self._authorization_code = None # auth codes are single-use + return token + + token = cast(AccessToken, None) + for refresh_token in self._client.get_cached_refresh_tokens(scopes): + if "secret" in refresh_token: + token = await self._client.obtain_token_by_refresh_token(scopes, refresh_token["secret"], **kwargs) + if token: + break + + if not token: + raise ClientAuthenticationError( + message="No authorization code, cached access token, or refresh token available." + ) + + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azd_cli.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azd_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..7162dc97f2aad1e60fe4a888d87fb011dfb045b7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azd_cli.py @@ -0,0 +1,195 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import asyncio +import os +import shutil +import sys +from typing import Any, List, Optional + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessToken +from .._internal import AsyncContextManager +from .._internal.decorators import log_get_token_async +from ... import CredentialUnavailableError +from ..._credentials.azd_cli import ( + AzureDeveloperCliCredential as _SyncAzureDeveloperCliCredential, + CLI_NOT_FOUND, + COMMAND_LINE, + EXECUTABLE_NAME, + get_safe_working_dir, + NOT_LOGGED_IN, + parse_token, + sanitize_output, +) +from ..._internal import resolve_tenant, within_dac, validate_tenant_id, validate_scope + + +class AzureDeveloperCliCredential(AsyncContextManager): + """Authenticates by requesting a token from the Azure Developer CLI. + + Azure Developer CLI is a command-line interface tool that allows developers to create, manage, and deploy + resources in Azure. It's built on top of the Azure CLI and provides additional functionality specific + to Azure developers. It allows users to authenticate as a user and/or a service principal against + `Microsoft Entra ID <"https://learn.microsoft.com/azure/active-directory/fundamentals/">`__. + The AzureDeveloperCliCredential authenticates in a development environment and acquires a token on behalf of + the logged-in user or service principal in Azure Developer CLI. It acts as the Azure Developer CLI logged-in user + or service principal and executes an Azure CLI command underneath to authenticate the application against + Microsoft Entra ID. + + To use this credential, the developer needs to authenticate locally in Azure Developer CLI using one of the + commands below: + + * Run "azd auth login" in Azure Developer CLI to authenticate interactively as a user. + * Run "azd auth login --client-id 'client_id' --client-secret 'client_secret' --tenant-id 'tenant_id'" + to authenticate as a service principal. + + You may need to repeat this process after a certain time period, depending on the refresh token validity in your + organization. Generally, the refresh token validity period is a few weeks to a few months. + AzureDeveloperCliCredential will prompt you to sign in again. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure Developer CLI process to respond. Defaults + to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START azure_developer_cli_credential_async] + :end-before: [END azure_developer_cli_credential_async] + :language: python + :dedent: 4 + :caption: Create an AzureDeveloperCliCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + self.tenant_id = tenant_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + @log_get_token_async + async def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke the Azure Developer CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked the Azure Developer CLI + but didn't receive an access token. + """ + # only ProactorEventLoop supports subprocesses on Windows (and it isn't the default loop on Python < 3.8) + if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop): + return _SyncAzureDeveloperCliCredential().get_token(*scopes, tenant_id=tenant_id, **kwargs) + + if not scopes: + raise ValueError("Missing scope in request. \n") + + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + commandString = " --scope ".join(scopes) + command = COMMAND_LINE.format(commandString) + tenant = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + + if tenant: + command += " --tenant-id " + tenant + output = await _run_command(command, self._process_timeout) + + token = parse_token(output) + if not token: + sanitized_output = sanitize_output(output) + message = ( + f"Unexpected output from Azure Developer CLI: '{sanitized_output}'. \n" + f"To mitigate this issue, please refer to the troubleshooting guidelines here at " + f"https://aka.ms/azsdk/python/identity/azdevclicredential/troubleshoot." + ) + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) + + return token + + async def close(self) -> None: + """Calling this method is unnecessary""" + + +async def _run_command(command: str, timeout: int) -> str: + # Ensure executable exists in PATH first. This avoids a subprocess call that would fail anyway. + if shutil.which(EXECUTABLE_NAME) is None: + raise CredentialUnavailableError(message=CLI_NOT_FOUND) + + if sys.platform.startswith("win"): + args = ("cmd", "/c " + command) + else: + args = ("/bin/sh", "-c", command) + + working_directory = get_safe_working_dir() + + try: + proc = await asyncio.create_subprocess_exec( + *args, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + stdin=asyncio.subprocess.DEVNULL, + cwd=working_directory, + env=dict(os.environ, NO_COLOR="true"), + ) + stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout) + output = stdout_b.decode() + stderr = stderr_b.decode() + except OSError as ex: + # failed to execute 'cmd' or '/bin/sh' + error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0])) + raise error from ex + except asyncio.TimeoutError as ex: + proc.kill() + raise CredentialUnavailableError(message="Timed out waiting for Azure Developer CLI") from ex + + if proc.returncode == 0: + return output + + # Fallback check in case the executable is not found while executing subprocess. + if proc.returncode == 127 or stderr.startswith("'azd' is not recognized"): + raise CredentialUnavailableError(CLI_NOT_FOUND) + + if "not logged in, run `azd auth login` to login" in stderr and "AADSTS" not in stderr: + raise CredentialUnavailableError(message=NOT_LOGGED_IN) + + message = sanitize_output(stderr) if stderr else "Failed to invoke Azure Developer CLI" + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_arc.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_arc.py new file mode 100644 index 0000000000000000000000000000000000000000..867df88b02302abfb9bfafab9dd2b899cca922c5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_arc.py @@ -0,0 +1,45 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Optional, Any + +from azure.core.pipeline.policies import AsyncHTTPPolicy +from azure.core.pipeline import PipelineRequest, PipelineResponse +from .._internal.managed_identity_base import AsyncManagedIdentityBase +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._constants import EnvironmentVariables +from ..._credentials.azure_arc import _get_request, _get_secret_key + + +class AzureArcCredential(AsyncManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[AsyncManagedIdentityClient]: + url = os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT) + imds = os.environ.get(EnvironmentVariables.IMDS_ENDPOINT) + if url and imds: + return AsyncManagedIdentityClient( + _per_retry_policies=[ArcChallengeAuthPolicy()], + request_factory=functools.partial(_get_request, url), + **kwargs + ) + return None + + def get_unavailable_message(self) -> str: + return "Azure Arc managed identity configuration not found in environment" + + +class ArcChallengeAuthPolicy(AsyncHTTPPolicy): + """Policy for handling Azure Arc's challenge authentication""" + + async def send(self, request: PipelineRequest) -> PipelineResponse: + request.http_request.headers["Metadata"] = "true" + response = await self.next.send(request) + + if response.http_response.status_code == 401: + secret_key = _get_secret_key(response) + request.http_request.headers["Authorization"] = "Basic {}".format(secret_key) + response = await self.next.send(request) + + return response diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_cli.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..ac8b88c0a848d66e968756ef3e9dc42ed402ed42 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_cli.py @@ -0,0 +1,173 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import asyncio +import os +import shutil +import sys +from typing import Any, List, Optional + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessToken +from .._internal import AsyncContextManager +from .._internal.decorators import log_get_token_async +from ... import CredentialUnavailableError +from ..._credentials.azure_cli import ( + AzureCliCredential as _SyncAzureCliCredential, + CLI_NOT_FOUND, + COMMAND_LINE, + EXECUTABLE_NAME, + get_safe_working_dir, + NOT_LOGGED_IN, + parse_token, + sanitize_output, +) +from ..._internal import _scopes_to_resource, resolve_tenant, within_dac, validate_tenant_id, validate_scope + + +class AzureCliCredential(AsyncContextManager): + """Authenticates by requesting a token from the Azure CLI. + + This requires previously logging in to Azure via "az login", and will use the CLI's currently logged in identity. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure CLI process to respond. Defaults to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_azure_cli_credential_async] + :end-before: [END create_azure_cli_credential_async] + :language: python + :dedent: 4 + :caption: Create an AzureCliCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + self.tenant_id = tenant_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + @log_get_token_async + async def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke the Azure CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked the Azure CLI but didn't + receive an access token. + """ + # only ProactorEventLoop supports subprocesses on Windows (and it isn't the default loop on Python < 3.8) + if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop): + return _SyncAzureCliCredential().get_token(*scopes, tenant_id=tenant_id, **kwargs) + + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + resource = _scopes_to_resource(*scopes) + command = COMMAND_LINE.format(resource) + tenant = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + + if tenant: + command += " --tenant " + tenant + output = await _run_command(command, self._process_timeout) + + token = parse_token(output) + if not token: + sanitized_output = sanitize_output(output) + message = ( + f"Unexpected output from Azure CLI: '{sanitized_output}'. \n" + f"To mitigate this issue, please refer to the troubleshooting guidelines here at " + f"https://aka.ms/azsdk/python/identity/azclicredential/troubleshoot." + ) + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) + + return token + + async def close(self) -> None: + """Calling this method is unnecessary""" + + +async def _run_command(command: str, timeout: int) -> str: + # Ensure executable exists in PATH first. This avoids a subprocess call that would fail anyway. + if shutil.which(EXECUTABLE_NAME) is None: + raise CredentialUnavailableError(message=CLI_NOT_FOUND) + + if sys.platform.startswith("win"): + args = ("cmd", "/c " + command) + else: + args = ("/bin/sh", "-c", command) + + working_directory = get_safe_working_dir() + + try: + proc = await asyncio.create_subprocess_exec( + *args, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + stdin=asyncio.subprocess.DEVNULL, + cwd=working_directory, + env=dict(os.environ, AZURE_CORE_NO_COLOR="true"), + ) + stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout) + output = stdout_b.decode() + stderr = stderr_b.decode() + except OSError as ex: + # failed to execute 'cmd' or '/bin/sh' + error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0])) + raise error from ex + except asyncio.TimeoutError as ex: + proc.kill() + raise CredentialUnavailableError(message="Timed out waiting for Azure CLI") from ex + + if proc.returncode == 0: + return output + + # Fallback check in case the executable is not found while executing subprocess. + if proc.returncode == 127 or stderr.startswith("'az' is not recognized"): + raise CredentialUnavailableError(CLI_NOT_FOUND) + + if ("az login" in stderr or "az account set" in stderr) and "AADSTS" not in stderr: + raise CredentialUnavailableError(message=NOT_LOGGED_IN) + + message = sanitize_output(stderr) if stderr else "Failed to invoke Azure CLI" + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_ml.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_ml.py new file mode 100644 index 0000000000000000000000000000000000000000..ce54d9e80219bb7b1cb7ce31e2eaf95820d4a169 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_ml.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any + +from .._internal.managed_identity_base import AsyncManagedIdentityBase +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._credentials.azure_ml import _get_client_args + + +class AzureMLCredential(AsyncManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[AsyncManagedIdentityClient]: + client_args = _get_client_args(**kwargs) + if client_args: + return AsyncManagedIdentityClient(**client_args) + return None + + def get_unavailable_message(self) -> str: + return "Azure ML managed identity configuration not found in environment" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_powershell.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_powershell.py new file mode 100644 index 0000000000000000000000000000000000000000..c8b5584ad23575f871d851dd88eb666b813b834c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/azure_powershell.py @@ -0,0 +1,150 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import asyncio +import sys +from typing import Any, cast, List, Optional +from azure.core.credentials import AccessToken + +from .._internal import AsyncContextManager +from .._internal.decorators import log_get_token_async +from ... import CredentialUnavailableError +from ..._credentials.azure_powershell import ( + AzurePowerShellCredential as _SyncCredential, + get_command_line, + get_safe_working_dir, + raise_for_error, + parse_token, +) +from ..._internal import resolve_tenant, validate_tenant_id, validate_scope + + +class AzurePowerShellCredential(AsyncContextManager): + """Authenticates by requesting a token from Azure PowerShell. + + This requires previously logging in to Azure via "Connect-AzAccount", and will use the currently logged in identity. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure PowerShell process to respond. Defaults to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_azure_power_shell_credential_async] + :end-before: [END create_azure_power_shell_credential_async] + :language: python + :dedent: 4 + :caption: Create an AzurePowerShellCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + self.tenant_id = tenant_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + @log_get_token_async + async def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke Azure PowerShell, or + no account is authenticated + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked Azure PowerShell but didn't + receive an access token + """ + # only ProactorEventLoop supports subprocesses on Windows (and it isn't the default loop on Python < 3.8) + if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop): + return _SyncCredential().get_token(*scopes, tenant_id=tenant_id, **kwargs) + + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + tenant_id = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + command_line = get_command_line(scopes, tenant_id) + output = await run_command_line(command_line, self._process_timeout) + token = parse_token(output) + return token + + async def close(self) -> None: + """Calling this method is unnecessary""" + + +async def run_command_line(command_line: List[str], timeout: int) -> str: + try: + proc = await start_process(command_line) + stdout, stderr = await asyncio.wait_for(proc.communicate(), 10) + if sys.platform.startswith("win") and b"' is not recognized" in stderr: + # pwsh.exe isn't on the path; try powershell.exe + command_line[-1] = command_line[-1].replace("pwsh", "powershell", 1) + proc = await start_process(command_line) + stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout) + + except OSError as ex: + # failed to execute "cmd" or "/bin/sh"; Azure PowerShell may or may not be installed + error = CredentialUnavailableError( + message='Failed to execute "{}".\n' + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/powershellcredential/troubleshoot.".format(command_line[0]) + ) + raise error from ex + except asyncio.TimeoutError as ex: + proc.kill() + raise CredentialUnavailableError( + message="Timed out waiting for Azure PowerShell.\n" + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/powershellcredential/troubleshoot." + ) from ex + + decoded_stdout = stdout.decode() + + # casting because mypy infers Optional[int]; however, when proc.returncode is None, + # we handled TimeoutError above and therefore don't execute this line + raise_for_error(cast(int, proc.returncode), decoded_stdout, stderr.decode()) + return decoded_stdout + + +async def start_process(command_line): + working_directory = get_safe_working_dir() + proc = await asyncio.create_subprocess_exec( + *command_line, + cwd=working_directory, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + stdin=asyncio.subprocess.DEVNULL, + ) + return proc diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/certificate.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/certificate.py new file mode 100644 index 0000000000000000000000000000000000000000..bf293db10df92159113adbe83b79307fa75ea43c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/certificate.py @@ -0,0 +1,79 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import TypeVar, Optional, Any + +from azure.core.credentials import AccessToken +from .._internal import AadClient, AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin +from ..._credentials.certificate import get_client_credential +from ..._internal import AadClientCertificate, validate_tenant_id + +T = TypeVar("T", bound="CertificateCredential") + + +class CertificateCredential(AsyncContextManager, GetTokenMixin): + """Authenticates as a service principal using a certificate. + + The certificate must have an RSA private key, because this credential signs assertions using RS256. See + `Microsoft Entra ID documentation + `_ + for more information on configuring certificate authentication. + + :param str tenant_id: ID of the service principal's tenant. Also called its 'directory' ID. + :param str client_id: The service principal's client ID + :param str certificate_path: Path to a PEM-encoded certificate file including the private key. If not provided, + `certificate_data` is required. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword bytes certificate_data: The bytes of a certificate in PEM format, including the private key + :keyword password: The certificate's password. If a unicode string, it will be encoded as UTF-8. If the certificate + requires a different encoding, pass appropriately encoded bytes instead. + :paramtype password: str or bytes + :keyword cache_persistence_options: Configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_certificate_credential_async] + :end-before: [END create_certificate_credential_async] + :language: python + :dedent: 4 + :caption: Create a CertificateCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, certificate_path: Optional[str] = None, **kwargs: Any) -> None: + validate_tenant_id(tenant_id) + + client_credential = get_client_credential(certificate_path, **kwargs) + + self._certificate = AadClientCertificate( + client_credential["private_key"], password=client_credential.get("passphrase") + ) + + self._client = AadClient(tenant_id, client_id, **kwargs) + self._client_id = client_id + super().__init__() + + async def __aenter__(self: T) -> T: + await self._client.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + + await self._client.__aexit__() + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + return await self._client.obtain_token_by_client_certificate(scopes, self._certificate, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/chained.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/chained.py new file mode 100644 index 0000000000000000000000000000000000000000..fa1ce44012c96ce0daa6f366a5af214e5de27872 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/chained.py @@ -0,0 +1,107 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import asyncio +import logging +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessToken +from .._internal import AsyncContextManager +from ... import CredentialUnavailableError +from ..._credentials.chained import _get_error_message +from ..._internal import within_credential_chain + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + +_LOGGER = logging.getLogger(__name__) + + +class ChainedTokenCredential(AsyncContextManager): + """A sequence of credentials that is itself a credential. + + Its :func:`get_token` method calls ``get_token`` on each credential in the sequence, in order, returning the first + valid token received. + + :param credentials: credential instances to form the chain + :type credentials: ~azure.core.credentials.AsyncTokenCredential + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_chained_token_credential_async] + :end-before: [END create_chained_token_credential_async] + :language: python + :dedent: 4 + :caption: Create a ChainedTokenCredential. + """ + + def __init__(self, *credentials: "AsyncTokenCredential") -> None: + if not credentials: + raise ValueError("at least one credential is required") + + self._successful_credential = None # type: Optional[AsyncTokenCredential] + self.credentials = credentials + + async def close(self) -> None: + """Close the transport sessions of all credentials in the chain.""" + + await asyncio.gather(*(credential.close() for credential in self.credentials)) + + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Asynchronously request a token from each credential, in order, returning the first token received. + + If no credential provides a token, raises :class:`azure.core.exceptions.ClientAuthenticationError` + with an error message from each credential. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: no credential in the chain provided a token + """ + within_credential_chain.set(True) + history = [] + for credential in self.credentials: + try: + token = await credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + _LOGGER.info("%s acquired a token from %s", self.__class__.__name__, credential.__class__.__name__) + self._successful_credential = credential + within_credential_chain.set(False) + return token + except CredentialUnavailableError as ex: + # credential didn't attempt authentication because it lacks required data or state -> continue + history.append((credential, ex.message)) + except Exception as ex: # pylint: disable=broad-except + # credential failed to authenticate, or something unexpectedly raised -> break + history.append((credential, str(ex))) + _LOGGER.debug( + '%s.get_token failed: %s raised unexpected error "%s"', + self.__class__.__name__, + credential.__class__.__name__, + ex, + exc_info=True, + ) + break + + within_credential_chain.set(False) + attempts = _get_error_message(history) + message = ( + self.__class__.__name__ + + " failed to retrieve a token from the included credentials." + + attempts + + "\nTo mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/defaultazurecredential/troubleshoot." + ) + raise ClientAuthenticationError(message=message) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/client_assertion.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/client_assertion.py new file mode 100644 index 0000000000000000000000000000000000000000..2475cf3ef92f51f9cae107770db37d079837e827 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/client_assertion.py @@ -0,0 +1,60 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Callable, Optional + +from azure.core.credentials import AccessToken +from .._internal import AadClient, AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin + + +class ClientAssertionCredential(AsyncContextManager, GetTokenMixin): + """Authenticates a service principal with a JWT assertion. + + This credential is for advanced scenarios. :class:`~azure.identity.CertificateCredential` has a more + convenient API for the most common assertion scenario, authenticating a service principal with a certificate. + + :param str tenant_id: ID of the principal's tenant. Also called its "directory" ID. + :param str client_id: The principal's client ID + :param func: A callable that returns a string assertion. The credential will call this every time it + acquires a new token. + :paramtype func: Callable[[], str] + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud (which is the default). + :class:`~azure.identity.AzureAuthorityHosts` defines authorities for other clouds. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_client_assertion_credential_async] + :end-before: [END create_client_assertion_credential_async] + :language: python + :dedent: 4 + :caption: Create a ClientAssertionCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, func: Callable[[], str], **kwargs: Any) -> None: + self._func = func + self._client = AadClient(tenant_id, client_id, **kwargs) + super().__init__(**kwargs) + + async def __aenter__(self): + await self._client.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + await self._client.close() + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + assertion = self._func() + token = await self._client.obtain_token_by_jwt_assertion(scopes, assertion, **kwargs) + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/client_secret.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/client_secret.py new file mode 100644 index 0000000000000000000000000000000000000000..94739ee66c54f0c554c53e44adc7815ee9b1faff --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/client_secret.py @@ -0,0 +1,69 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, TypeVar, Any + +from azure.core.credentials import AccessToken +from .._internal import AadClient, AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin +from ..._internal import validate_tenant_id + +T = TypeVar("T", bound="ClientSecretCredential") + + +class ClientSecretCredential(AsyncContextManager, GetTokenMixin): + """Authenticates as a service principal using a client secret. + + :param str tenant_id: ID of the service principal's tenant. Also called its 'directory' ID. + :param str client_id: The service principal's client ID + :param str client_secret: One of the service principal's client secrets + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword cache_persistence_options: Configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_client_secret_credential_async] + :end-before: [END create_client_secret_credential_async] + :language: python + :dedent: 4 + :caption: Create a ClientSecretCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, client_secret: str, **kwargs: Any) -> None: + if not client_id: + raise ValueError("client_id should be the id of a Microsoft Entra application") + if not client_secret: + raise ValueError("secret should be a Microsoft Entra application's client secret") + if not tenant_id: + raise ValueError("tenant_id should be a Microsoft Entra tenant's id (also called its 'directory id')") + validate_tenant_id(tenant_id) + + self._client = AadClient(tenant_id, client_id, **kwargs) + self._client_id = client_id + self._secret = client_secret + super().__init__() + + async def __aenter__(self: T) -> T: + await self._client.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + + await self._client.__aexit__() + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + return await self._client.obtain_token_by_client_secret(scopes, self._secret, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/cloud_shell.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/cloud_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..c4aefe44e542c03363760ede5b0fe983f26f7022 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/cloud_shell.py @@ -0,0 +1,25 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Optional, Any + +from .._internal.managed_identity_base import AsyncManagedIdentityBase +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._constants import EnvironmentVariables +from ..._credentials.cloud_shell import _get_request + + +class CloudShellCredential(AsyncManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[AsyncManagedIdentityClient]: + url = os.environ.get(EnvironmentVariables.MSI_ENDPOINT) + if url: + return AsyncManagedIdentityClient( + request_factory=functools.partial(_get_request, url), base_headers={"Metadata": "true"}, **kwargs + ) + return None + + def get_unavailable_message(self) -> str: + return "Cloud Shell managed identity configuration not found in environment" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/default.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/default.py new file mode 100644 index 0000000000000000000000000000000000000000..4accfe778a4bbec6900a3804551c3d72bcf191c2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/default.py @@ -0,0 +1,203 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import List, Optional, TYPE_CHECKING, Any, cast + +from azure.core.credentials import AccessToken +from ..._constants import EnvironmentVariables +from ..._internal import get_default_authority, normalize_authority, within_dac +from .azure_cli import AzureCliCredential +from .azd_cli import AzureDeveloperCliCredential +from .azure_powershell import AzurePowerShellCredential +from .chained import ChainedTokenCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from .shared_cache import SharedTokenCacheCredential +from .vscode import VisualStudioCodeCredential +from .workload_identity import WorkloadIdentityCredential + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + +_LOGGER = logging.getLogger(__name__) + + +class DefaultAzureCredential(ChainedTokenCredential): + """A default credential capable of handling most Azure SDK authentication scenarios. + + The identity it uses depends on the environment. When an access token is needed, it requests one using these + identities in turn, stopping when one provides a token: + + 1. A service principal configured by environment variables. See :class:`~azure.identity.aio.EnvironmentCredential` + for more details. + 2. WorkloadIdentityCredential if environment variable configuration is set by the Azure workload + identity webhook. + 3. An Azure managed identity. See :class:`~azure.identity.aio.ManagedIdentityCredential` for more details. + 4. On Windows only: a user who has signed in with a Microsoft application, such as Visual Studio. If multiple + identities are in the cache, then the value of the environment variable ``AZURE_USERNAME`` is used to select + which identity to use. See :class:`~azure.identity.aio.SharedTokenCacheCredential` for more details. + 5. The identity currently logged in to the Azure CLI. + 6. The identity currently logged in to Azure PowerShell. + 7. The identity currently logged in to the Azure Developer CLI. + + This default behavior is configurable with keyword arguments. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. Managed identities ignore this because they reside in a single cloud. + :keyword bool exclude_workload_identity_credential: Whether to exclude the workload identity from the credential. + Defaults to **False**. + :keyword bool exclude_developer_cli_credential: Whether to exclude the Azure Developer CLI + from the credential. Defaults to **False**. + :keyword bool exclude_cli_credential: Whether to exclude the Azure CLI from the credential. Defaults to **False**. + :keyword bool exclude_environment_credential: Whether to exclude a service principal configured by environment + variables from the credential. Defaults to **False**. + :keyword bool exclude_powershell_credential: Whether to exclude Azure PowerShell. Defaults to **False**. + :keyword bool exclude_visual_studio_code_credential: Whether to exclude stored credential from VS Code. + Defaults to **True**. + :keyword bool exclude_managed_identity_credential: Whether to exclude managed identity from the credential. + Defaults to **False**. + :keyword bool exclude_shared_token_cache_credential: Whether to exclude the shared token cache. Defaults to + **False**. + :keyword str managed_identity_client_id: The client ID of a user-assigned managed identity. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, a system-assigned identity will be used. + :keyword str workload_identity_client_id: The client ID of an identity assigned to the pod. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, the pod's default identity will be used. + :keyword str workload_identity_tenant_id: Preferred tenant for :class:`~azure.identity.WorkloadIdentityCredential`. + Defaults to the value of environment variable AZURE_TENANT_ID, if any. + :keyword str shared_cache_username: Preferred username for :class:`~azure.identity.aio.SharedTokenCacheCredential`. + Defaults to the value of environment variable AZURE_USERNAME, if any. + :keyword str shared_cache_tenant_id: Preferred tenant for :class:`~azure.identity.aio.SharedTokenCacheCredential`. + Defaults to the value of environment variable AZURE_TENANT_ID, if any. + :keyword str visual_studio_code_tenant_id: Tenant ID to use when authenticating with + :class:`~azure.identity.aio.VisualStudioCodeCredential`. Defaults to the "Azure: Tenant" setting in VS Code's + user settings or, when that setting has no value, the "organizations" tenant, which supports only Azure Active + Directory work or school accounts. + :keyword int process_timeout: The timeout in seconds to use for developer credentials that run + subprocesses (e.g. AzureCliCredential, AzurePowerShellCredential). Defaults to **10** seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_default_credential_async] + :end-before: [END create_default_credential_async] + :language: python + :dedent: 4 + :caption: Create a DefaultAzureCredential. + """ + + def __init__(self, **kwargs: Any) -> None: + if "tenant_id" in kwargs: + raise TypeError("'tenant_id' is not supported in DefaultAzureCredential.") + + authority = kwargs.pop("authority", None) + + vscode_tenant_id = kwargs.pop( + "visual_studio_code_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + vscode_args = dict(kwargs) + if authority: + vscode_args["authority"] = authority + if vscode_tenant_id: + vscode_args["tenant_id"] = vscode_tenant_id + + authority = normalize_authority(authority) if authority else get_default_authority() + + shared_cache_username = kwargs.pop("shared_cache_username", os.environ.get(EnvironmentVariables.AZURE_USERNAME)) + shared_cache_tenant_id = kwargs.pop( + "shared_cache_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + + managed_identity_client_id = kwargs.pop( + "managed_identity_client_id", os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + ) + workload_identity_client_id = kwargs.pop("workload_identity_client_id", managed_identity_client_id) + workload_identity_tenant_id = kwargs.pop( + "workload_identity_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + + vscode_tenant_id = kwargs.pop( + "visual_studio_code_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + + process_timeout = kwargs.pop("process_timeout", 10) + + exclude_workload_identity_credential = kwargs.pop("exclude_workload_identity_credential", False) + exclude_visual_studio_code_credential = kwargs.pop("exclude_visual_studio_code_credential", True) + exclude_developer_cli_credential = kwargs.pop("exclude_developer_cli_credential", False) + exclude_cli_credential = kwargs.pop("exclude_cli_credential", False) + exclude_environment_credential = kwargs.pop("exclude_environment_credential", False) + exclude_managed_identity_credential = kwargs.pop("exclude_managed_identity_credential", False) + exclude_shared_token_cache_credential = kwargs.pop("exclude_shared_token_cache_credential", False) + exclude_powershell_credential = kwargs.pop("exclude_powershell_credential", False) + + credentials = [] # type: List[AsyncTokenCredential] + if not exclude_environment_credential: + credentials.append(EnvironmentCredential(authority=authority, _within_dac=True, **kwargs)) + if not exclude_workload_identity_credential: + if all(os.environ.get(var) for var in EnvironmentVariables.WORKLOAD_IDENTITY_VARS): + client_id = workload_identity_client_id + credentials.append( + WorkloadIdentityCredential( + client_id=cast(str, client_id), + tenant_id=workload_identity_tenant_id, + file=os.environ[EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE], + **kwargs + ) + ) + if not exclude_managed_identity_credential: + credentials.append( + ManagedIdentityCredential( + client_id=managed_identity_client_id, + _exclude_workload_identity_credential=exclude_workload_identity_credential, + **kwargs + ) + ) + if not exclude_shared_token_cache_credential and SharedTokenCacheCredential.supported(): + try: + # username and/or tenant_id are only required when the cache contains tokens for multiple identities + shared_cache = SharedTokenCacheCredential( + username=shared_cache_username, tenant_id=shared_cache_tenant_id, authority=authority, **kwargs + ) + credentials.append(shared_cache) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.info("Shared token cache is unavailable: '%s'", ex) + if not exclude_visual_studio_code_credential: + credentials.append(VisualStudioCodeCredential(**vscode_args)) + if not exclude_cli_credential: + credentials.append(AzureCliCredential(process_timeout=process_timeout)) + if not exclude_powershell_credential: + credentials.append(AzurePowerShellCredential(process_timeout=process_timeout)) + if not exclude_developer_cli_credential: + credentials.append(AzureDeveloperCliCredential(process_timeout=process_timeout)) + + super().__init__(*credentials) + + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Asynchronously request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + return await self._successful_credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + within_dac.set(True) + token = await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + within_dac.set(False) + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/environment.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..68d2f8555e3e32751171b054c4603a5852b23976 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/environment.py @@ -0,0 +1,123 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import Optional, Union, Any + +from azure.core.credentials import AccessToken +from .._internal.decorators import log_get_token_async +from ... import CredentialUnavailableError +from ..._constants import EnvironmentVariables +from .._internal import AsyncContextManager +from .certificate import CertificateCredential +from .client_secret import ClientSecretCredential + +_LOGGER = logging.getLogger(__name__) + + +class EnvironmentCredential(AsyncContextManager): + """A credential configured by environment variables. + + This credential is capable of authenticating as a service principal using a client secret or a certificate, or as + a user with a username and password. Configuration is attempted in this order, using these environment variables: + + Service principal with secret: + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its 'directory' ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + - **AZURE_CLIENT_SECRET**: one of the service principal's client secrets + - **AZURE_AUTHORITY_HOST**: authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud, which is the default + when no value is given. + + Service principal with certificate: + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its 'directory' ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + - **AZURE_CLIENT_CERTIFICATE_PATH**: path to a PEM or PKCS12 certificate file including the private key. + - **AZURE_CLIENT_CERTIFICATE_PASSWORD**: (optional) password of the certificate file, if any. + - **AZURE_AUTHORITY_HOST**: authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud, which is the default + when no value is given. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_environment_credential_async] + :end-before: [END create_environment_credential_async] + :language: python + :dedent: 4 + :caption: Create an EnvironmentCredential. + """ + + def __init__(self, **kwargs: Any) -> None: + self._credential: Optional[Union[CertificateCredential, ClientSecretCredential]] = None + + if all(os.environ.get(v) is not None for v in EnvironmentVariables.CLIENT_SECRET_VARS): + self._credential = ClientSecretCredential( + client_id=os.environ[EnvironmentVariables.AZURE_CLIENT_ID], + client_secret=os.environ[EnvironmentVariables.AZURE_CLIENT_SECRET], + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + **kwargs + ) + elif all(os.environ.get(v) is not None for v in EnvironmentVariables.CERT_VARS): + self._credential = CertificateCredential( + client_id=os.environ[EnvironmentVariables.AZURE_CLIENT_ID], + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + certificate_path=os.environ[EnvironmentVariables.AZURE_CLIENT_CERTIFICATE_PATH], + password=os.environ.get(EnvironmentVariables.AZURE_CLIENT_CERTIFICATE_PASSWORD), + **kwargs + ) + + if self._credential: + _LOGGER.info("Environment is configured for %s", self._credential.__class__.__name__) + else: + expected_variables = set(EnvironmentVariables.CERT_VARS + EnvironmentVariables.CLIENT_SECRET_VARS) + set_variables = [v for v in expected_variables if v in os.environ] + if set_variables: + _LOGGER.log( + logging.INFO if kwargs.get("_within_dac") else logging.WARNING, + "Incomplete environment configuration for EnvironmentCredential. These variables are set: %s", + ", ".join(set_variables), + ) + else: + _LOGGER.info("No environment configuration found.") + + async def __aenter__(self): + if self._credential: + await self._credential.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + + if self._credential: + await self._credential.__aexit__() + + @log_get_token_async + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Asynchronously request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: environment variable configuration is incomplete + """ + if not self._credential: + message = ( + "EnvironmentCredential authentication unavailable. Environment variables are not fully configured.\n" + "Visit https://aka.ms/azsdk/python/identity/environmentcredential/troubleshoot to troubleshoot " + "this issue." + ) + raise CredentialUnavailableError(message=message) + return await self._credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/imds.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/imds.py new file mode 100644 index 0000000000000000000000000000000000000000..501e4e53080f3f1b2a9a6fcf1b6c58dbf1c0c5b6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/imds.py @@ -0,0 +1,84 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +from typing import Optional, TypeVar, Any + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError +from azure.core.credentials import AccessToken +from ... import CredentialUnavailableError +from ..._constants import EnvironmentVariables +from .._internal import AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._internal import within_credential_chain +from ..._credentials.imds import _get_request, _check_forbidden_response, PIPELINE_SETTINGS + +T = TypeVar("T", bound="ImdsCredential") + + +class ImdsCredential(AsyncContextManager, GetTokenMixin): + def __init__(self, **kwargs: Any) -> None: + super().__init__() + + self._client = AsyncManagedIdentityClient(_get_request, **dict(PIPELINE_SETTINGS, **kwargs)) + if EnvironmentVariables.AZURE_POD_IDENTITY_AUTHORITY_HOST in os.environ: + self._endpoint_available: Optional[bool] = True + else: + self._endpoint_available = None + self._user_assigned_identity = "client_id" in kwargs or "identity_config" in kwargs + + async def __aenter__(self: T) -> T: + await self._client.__aenter__() + return self + + async def close(self) -> None: + await self._client.close() + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + return self._client.get_cached_token(*scopes) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: # pylint:disable=unused-argument + + if within_credential_chain.get() and not self._endpoint_available: + # If within a chain (e.g. DefaultAzureCredential), we do a quick check to see if the IMDS endpoint + # is available to avoid hanging for a long time if the endpoint isn't available. + try: + await self._client.request_token(*scopes, connection_timeout=1, retry_total=0) + self._endpoint_available = True + except HttpResponseError as ex: + # IMDS responded + _check_forbidden_response(ex) + self._endpoint_available = True + except Exception as ex: # pylint:disable=broad-except + error_message = ( + "ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint." + ) + raise CredentialUnavailableError(message=error_message) from ex + + try: + token = await self._client.request_token(*scopes, headers={"Metadata": "true"}) + except HttpResponseError as ex: + # 400 in response to a token request indicates managed identity is disabled, + # or the identity with the specified client_id is not available + if ex.status_code == 400: + error_message = "ManagedIdentityCredential authentication unavailable. " + if self._user_assigned_identity: + error_message += "The requested identity has not been assigned to this resource." + else: + error_message += "No identity has been assigned to this resource." + + if ex.message: + error_message += f" Error: {ex.message}" + + raise CredentialUnavailableError(message=error_message) from ex + + _check_forbidden_response(ex) + # any other error is unexpected + raise ClientAuthenticationError(message=ex.message, response=ex.response) from ex + except Exception as ex: # pylint:disable=broad-except + # if anything else was raised, assume the endpoint is unavailable + error_message = "ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint." + raise CredentialUnavailableError(error_message) from ex + return token diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/managed_identity.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/managed_identity.py new file mode 100644 index 0000000000000000000000000000000000000000..279b1c88a1f1b6a66b8ffff5b6fbc3d6d0793ce6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/managed_identity.py @@ -0,0 +1,141 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import TYPE_CHECKING, Optional, Any + +from azure.core.credentials import AccessToken +from .._internal import AsyncContextManager +from .._internal.decorators import log_get_token_async +from ... import CredentialUnavailableError +from ..._constants import EnvironmentVariables + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + +_LOGGER = logging.getLogger(__name__) + + +class ManagedIdentityCredential(AsyncContextManager): + """Authenticates with an Azure managed identity in any hosting environment which supports managed identities. + + This credential defaults to using a system-assigned identity. To configure a user-assigned identity, use one of + the keyword arguments. See `Microsoft Entra ID documentation + `_ for more + information about configuring managed identity for applications. + + :keyword str client_id: a user-assigned identity's client ID or, when using Pod Identity, the client ID of an Azure + AD app registration. This argument is supported in all hosting environments. + :keyword identity_config: a mapping ``{parameter_name: value}`` specifying a user-assigned identity by its object + or resource ID, for example ``{"object_id": "..."}``. Check the documentation for your hosting environment to + learn what values it expects. + :paramtype identity_config: Mapping[str, str] + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_managed_identity_credential_async] + :end-before: [END create_managed_identity_credential_async] + :language: python + :dedent: 4 + :caption: Create a ManagedIdentityCredential. + """ + + def __init__(self, **kwargs: Any) -> None: + self._credential = None # type: Optional[AsyncTokenCredential] + exclude_workload_identity = kwargs.pop("_exclude_workload_identity_credential", False) + + if os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT): + if os.environ.get(EnvironmentVariables.IDENTITY_HEADER): + if os.environ.get(EnvironmentVariables.IDENTITY_SERVER_THUMBPRINT): + _LOGGER.info("%s will use Service Fabric managed identity", self.__class__.__name__) + from .service_fabric import ServiceFabricCredential + + self._credential = ServiceFabricCredential(**kwargs) + else: + _LOGGER.info("%s will use App Service managed identity", self.__class__.__name__) + from .app_service import AppServiceCredential + + self._credential = AppServiceCredential(**kwargs) + elif os.environ.get(EnvironmentVariables.IMDS_ENDPOINT): + _LOGGER.info("%s will use Azure Arc managed identity", self.__class__.__name__) + from .azure_arc import AzureArcCredential + + self._credential = AzureArcCredential(**kwargs) + else: + _LOGGER.info("%s will use Cloud Shell managed identity", self.__class__.__name__) + from .cloud_shell import CloudShellCredential + + self._credential = CloudShellCredential(**kwargs) + elif os.environ.get(EnvironmentVariables.MSI_ENDPOINT): + if os.environ.get(EnvironmentVariables.MSI_SECRET): + _LOGGER.info("%s will use Azure ML managed identity", self.__class__.__name__) + from .azure_ml import AzureMLCredential + + self._credential = AzureMLCredential(**kwargs) + else: + _LOGGER.info("%s will use Cloud Shell managed identity", self.__class__.__name__) + from .cloud_shell import CloudShellCredential + + self._credential = CloudShellCredential(**kwargs) + elif ( + all(os.environ.get(var) for var in EnvironmentVariables.WORKLOAD_IDENTITY_VARS) + and not exclude_workload_identity + ): + _LOGGER.info("%s will use workload identity", self.__class__.__name__) + from .workload_identity import WorkloadIdentityCredential + + client_id = kwargs.pop("client_id", None) or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + if not client_id: + raise ValueError('Configure the environment with a client ID or pass a value for "client_id" argument') + + self._credential = WorkloadIdentityCredential( + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + client_id=client_id, + file=os.environ[EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE], + **kwargs + ) + else: + from .imds import ImdsCredential + + _LOGGER.info("%s will use IMDS", self.__class__.__name__) + self._credential = ImdsCredential(**kwargs) + + async def __aenter__(self): + if self._credential: + await self._credential.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + if self._credential: + await self._credential.close() + + @log_get_token_async + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Asynchronously request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: not used by this credential; any value provided will be ignored. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: managed identity isn't available in the hosting environment + """ + if not self._credential: + raise CredentialUnavailableError( + message="No managed identity endpoint found. \n" + "The Target Azure platform could not be determined from environment variables. " + "Visit https://aka.ms/azsdk/python/identity/managedidentitycredential/troubleshoot to " + "troubleshoot this issue." + ) + return await self._credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/on_behalf_of.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/on_behalf_of.py new file mode 100644 index 0000000000000000000000000000000000000000..b56619bb3dcb379e6a8d82c83e6fb01ef23c5a22 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/on_behalf_of.py @@ -0,0 +1,120 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +from typing import Optional, Union, Any + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessToken +from .._internal import AadClient, AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin +from ..._credentials.certificate import get_client_credential +from ..._internal import AadClientCertificate, validate_tenant_id + +_LOGGER = logging.getLogger(__name__) + + +class OnBehalfOfCredential(AsyncContextManager, GetTokenMixin): + """Authenticates a service principal via the on-behalf-of flow. + + This flow is typically used by middle-tier services that authorize requests to other services with a delegated + user identity. Because this is not an interactive authentication flow, an application using it must have admin + consent for any delegated permissions before requesting tokens for them. See `Microsoft Entra ID documentation + `_ for a more detailed + description of the on-behalf-of flow. + + :param str tenant_id: ID of the service principal's tenant. Also called its "directory" ID. + :param str client_id: The service principal's client ID + :keyword str client_secret: Optional. A client secret to authenticate the service principal. + Either **client_secret** or **client_certificate** must be provided. + :keyword bytes client_certificate: Optional. The bytes of a certificate in PEM or PKCS12 format including + the private key to authenticate the service principal. Either **client_secret** or **client_certificate** must + be provided. + :keyword str user_assertion: Required. The access token the credential will use as the user assertion when + requesting on-behalf-of tokens + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword password: A certificate password. Used only when **client_certificate** is provided. If this value + is a unicode string, it will be encoded as UTF-8. If the certificate requires a different encoding, pass + appropriately encoded bytes instead. + :paramtype password: str or bytes + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_on_behalf_of_credential_async] + :end-before: [END create_on_behalf_of_credential_async] + :language: python + :dedent: 4 + :caption: Create an OnBehalfOfCredential. + """ + + def __init__( + self, + tenant_id: str, + client_id: str, + *, + client_certificate: Optional[bytes] = None, + client_secret: Optional[str] = None, + user_assertion: str, + **kwargs: Any + ) -> None: + super().__init__() + validate_tenant_id(tenant_id) + + self._assertion = user_assertion + + if client_certificate: + if client_secret: + raise ValueError('Specifying both "client_certificate" and "client_secret" is not valid.') + try: + cert = get_client_credential(None, kwargs.pop("password", None), client_certificate) + except ValueError as ex: + message = '"client_certificate" is not a valid certificate in PEM or PKCS12 format' + raise ValueError(message) from ex + self._client_credential: Union[str, AadClientCertificate] = AadClientCertificate( + cert["private_key"], password=cert.get("passphrase") + ) + elif client_secret: + self._client_credential = client_secret + else: + raise TypeError('Either "client_certificate" or "client_secret" must be provided') + + # note AadClient handles "authority" and any pipeline kwargs + self._client = AadClient(tenant_id, client_id, **kwargs) + + async def __aenter__(self): + await self._client.__aenter__() + return self + + async def close(self) -> None: + await self._client.close() + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + # Note we assume the cache has tokens for one user only. That's okay because each instance of this class is + # locked to a single user (assertion). This assumption will become unsafe if this class allows applications + # to change an instance's assertion. + refresh_tokens = self._client.get_cached_refresh_tokens(scopes) + if len(refresh_tokens) == 1: # there should be only one + try: + refresh_token = refresh_tokens[0]["secret"] + return await self._client.obtain_token_by_refresh_token_on_behalf_of( + scopes, self._client_credential, refresh_token, **kwargs + ) + except ClientAuthenticationError as ex: + _LOGGER.debug("silent authentication failed: %s", ex, exc_info=True) + except (IndexError, KeyError, TypeError) as ex: + # this is purely defensive, hasn't been observed in practice + _LOGGER.debug("silent authentication failed due to malformed refresh token: %s", ex, exc_info=True) + + # we don't have a refresh token, or silent auth failed: acquire a new token from the assertion + return await self._client.obtain_token_on_behalf_of(scopes, self._client_credential, self._assertion, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/service_fabric.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/service_fabric.py new file mode 100644 index 0000000000000000000000000000000000000000..7542ed127afc711a08df28a330de66080ad12da5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/service_fabric.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any + +from .._internal.managed_identity_base import AsyncManagedIdentityBase +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._credentials.service_fabric import _get_client_args + + +class ServiceFabricCredential(AsyncManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[AsyncManagedIdentityClient]: + client_args = _get_client_args(**kwargs) + if client_args: + return AsyncManagedIdentityClient(**client_args) + return None + + def get_unavailable_message(self) -> str: + return "Service Fabric managed identity configuration not found in environment" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/shared_cache.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/shared_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..d30304df4ce71dccc6187bf64144df039d7582bc --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/shared_cache.py @@ -0,0 +1,104 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Optional +from azure.core.credentials import AccessToken +from ..._internal.aad_client import AadClientBase +from ... import CredentialUnavailableError +from ..._constants import DEVELOPER_SIGN_ON_CLIENT_ID +from ..._internal.shared_token_cache import NO_TOKEN, SharedTokenCacheBase +from .._internal import AsyncContextManager +from .._internal.aad_client import AadClient +from .._internal.decorators import log_get_token_async + + +class SharedTokenCacheCredential(SharedTokenCacheBase, AsyncContextManager): + """Authenticates using tokens in the local cache shared between Microsoft applications. + + :param str username: + Username (typically an email address) of the user to authenticate as. This is required because the local cache + may contain tokens for multiple identities. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str tenant_id: a Microsoft Entra tenant ID. Used to select an account when the cache contains + tokens for multiple identities. + :keyword cache_persistence_options: configuration for persistent token caching. If not provided, the credential + will use the persistent cache shared by Microsoft development applications + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + """ + + async def __aenter__(self): + if self._client: + await self._client.__aenter__() # type: ignore + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + + if self._client: + await self._client.__aexit__() # type: ignore + + @log_get_token_async + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Get an access token for `scopes` from the shared cache. + + If no access token is cached, attempt to acquire one using a cached refresh token. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the cache is unavailable or contains insufficient user + information + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. Any error response from Microsoft Entra ID is available as the error's + ``response`` attribute. + """ + if not scopes: + raise ValueError("'get_token' requires at least one scope") + + if not self._client_initialized: + self._initialize_client() + + is_cae = bool(kwargs.get("enable_cae", False)) + token_cache = self._cae_cache if is_cae else self._cache + + # Try to load the cache if it is None. + if not token_cache: + token_cache = self._initialize_cache(is_cae=is_cae) + + # If the cache is still None, raise an error. + if not token_cache: + raise CredentialUnavailableError(message="Shared token cache unavailable") + + account = self._get_account(self._username, self._tenant_id, is_cae=is_cae) + + token = self._get_cached_access_token(scopes, account, is_cae=is_cae) + if token: + return token + + # try each refresh token, returning the first access token acquired + for refresh_token in self._get_refresh_tokens(account, is_cae=is_cae): + token = await self._client.obtain_token_by_refresh_token( + scopes, refresh_token, claims=claims, tenant_id=tenant_id, **kwargs + ) + return token + + raise CredentialUnavailableError(message=NO_TOKEN.format(account.get("username"))) + + def _get_auth_client(self, **kwargs: Any) -> AadClientBase: + return AadClient(client_id=DEVELOPER_SIGN_ON_CLIENT_ID, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/vscode.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/vscode.py new file mode 100644 index 0000000000000000000000000000000000000000..b0b160f67cdd052fd330c37bea6ae79c977888b7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/vscode.py @@ -0,0 +1,96 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import cast, Optional, Any + +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError +from ..._exceptions import CredentialUnavailableError +from .._internal import AsyncContextManager +from .._internal.aad_client import AadClient +from .._internal.get_token_mixin import GetTokenMixin +from .._internal.decorators import log_get_token_async +from ..._credentials.vscode import _VSCodeCredentialBase +from ..._internal import within_dac + + +class VisualStudioCodeCredential(_VSCodeCredentialBase, AsyncContextManager, GetTokenMixin): + """Authenticates as the Azure user signed in to Visual Studio Code via the 'Azure Account' extension. + + It's a `known issue `_ that this credential doesn't + work with `Azure Account extension `_ + versions newer than **0.9.11**. A long-term fix to this problem is in progress. In the meantime, consider + authenticating with :class:`AzureCliCredential`. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com". + This argument is required for a custom cloud and usually unnecessary otherwise. Defaults to the authority + matching the "Azure: Cloud" setting in VS Code's user settings or, when that setting has no value, the + authority for Azure Public Cloud. + :keyword str tenant_id: ID of the tenant the credential should authenticate in. Defaults to the "Azure: Tenant" + setting in VS Code's user settings or, when that setting has no value, the "organizations" tenant, which + supports only Microsoft Entra work or school accounts. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + """ + + async def __aenter__(self) -> "VisualStudioCodeCredential": + if self._client: + await self._client.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + + if self._client: + await self._client.__aexit__() + + @log_get_token_async + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes` as the user currently signed in to Visual Studio Code. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual + Studio Code + """ + if self._unavailable_reason: + error_message = ( + self._unavailable_reason + "\n" + "Visit https://aka.ms/azsdk/python/identity/vscodecredential/troubleshoot" + " to troubleshoot this issue." + ) + raise CredentialUnavailableError(message=error_message) + if not self._client: + raise CredentialUnavailableError("Initialization failed") + if within_dac.get(): + try: + token = await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + return token + except ClientAuthenticationError as ex: + raise CredentialUnavailableError(message=ex.message) from ex + return await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessToken]: + self._client = cast(AadClient, self._client) + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + refresh_token = self._get_refresh_token() + self._client = cast(AadClient, self._client) + return await self._client.obtain_token_by_refresh_token(scopes, refresh_token, **kwargs) + + def _get_client(self, **kwargs: Any) -> AadClient: + return AadClient(**kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/workload_identity.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/workload_identity.py new file mode 100644 index 0000000000000000000000000000000000000000..d580380902a168f584f2b0b86b4f71cfe1b3ec63 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_credentials/workload_identity.py @@ -0,0 +1,76 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +from typing import Any, Optional +from .client_assertion import ClientAssertionCredential +from ..._credentials.workload_identity import TokenFileMixin +from ..._constants import EnvironmentVariables + + +class WorkloadIdentityCredential(ClientAssertionCredential, TokenFileMixin): + """Authenticates using Microsoft Entra Workload ID. + + Workload identity authentication is a feature in Azure that allows applications running on virtual machines (VMs) + to access other Azure resources without the need for a service principal or managed identity. With workload + identity authentication, applications authenticate themselves using their own identity, rather than using a shared + service principal or managed identity. Under the hood, workload identity authentication uses the concept of Service + Account Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using + workload identity authentication, you can avoid the need to manage and rotate service principals or managed + identities for each application on each VM. Additionally, because SACs are created automatically and managed by + Azure, you don't need to worry about storing and securing sensitive credentials themselves. + + The WorkloadIdentityCredential supports Azure workload identity authentication on Azure Kubernetes and acquires + a token using the service account credentials available in the Azure Kubernetes environment. Refer + to `this workload identity overview `__ + for more information. + + :keyword str tenant_id: ID of the application's Microsoft Entra tenant. Also called its "directory" ID. + :keyword str client_id: The client ID of a Microsoft Entra app registration. + :keyword str token_file_path: The path to a file containing a Kubernetes service account token that authenticates + the identity. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START workload_identity_credential_async] + :end-before: [END workload_identity_credential_async] + :language: python + :dedent: 4 + :caption: Create a WorkloadIdentityCredential. + """ + + def __init__( + self, + *, + tenant_id: Optional[str] = None, + client_id: Optional[str] = None, + token_file_path: Optional[str] = None, + **kwargs: Any, + ) -> None: + tenant_id = tenant_id or os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + client_id = client_id or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + token_file_path = token_file_path or os.environ.get(EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE) + if not tenant_id: + raise ValueError( + "'tenant_id' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_TENANT_ID} environment variable" + ) + if not client_id: + raise ValueError( + "'client_id' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_CLIENT_ID} environment variable" + ) + if not token_file_path: + raise ValueError( + "'token_file_path' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE} environment variable" + ) + super().__init__( + tenant_id=tenant_id, + client_id=client_id, + func=self._get_service_account_token, + token_file_path=token_file_path, + **kwargs, + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..518217929cd87ef250efaed9a1057ac98e469fa5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/__init__.py @@ -0,0 +1,30 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +from types import TracebackType +from typing import Optional, Type + +from .aad_client import AadClient +from .decorators import wrap_exceptions + + +class AsyncContextManager(abc.ABC): + @abc.abstractmethod + async def close(self): + pass + + async def __aenter__(self): + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ) -> None: + await self.close() + + +__all__ = ["AadClient", "AsyncContextManager", "wrap_exceptions"] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/aad_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/aad_client.py new file mode 100644 index 0000000000000000000000000000000000000000..868f863d4f2b6adf9f72a7fe15bf5df1c6000127 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/aad_client.py @@ -0,0 +1,85 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import time +from typing import Iterable, Optional, Union + +from azure.core.credentials import AccessToken +from azure.core.pipeline import AsyncPipeline +from azure.core.pipeline.policies import AsyncHTTPPolicy, SansIOHTTPPolicy +from azure.core.pipeline.transport import HttpRequest +from ..._internal import AadClientCertificate +from ..._internal import AadClientBase +from ..._internal.pipeline import build_async_pipeline + +Policy = Union[AsyncHTTPPolicy, SansIOHTTPPolicy] + +# pylint:disable=invalid-overridden-method +class AadClient(AadClientBase): + async def __aenter__(self): + await self._pipeline.__aenter__() + return self + + async def __aexit__(self, *args): + await self.close() + + async def close(self) -> None: + """Close the client's transport session.""" + + await self._pipeline.__aexit__() + + async def obtain_token_by_authorization_code( + self, scopes: Iterable[str], code: str, redirect_uri: str, client_secret: Optional[str] = None, **kwargs + ) -> AccessToken: + request = self._get_auth_code_request( + scopes=scopes, code=code, redirect_uri=redirect_uri, client_secret=client_secret, **kwargs + ) + return await self._run_pipeline(request, **kwargs) + + async def obtain_token_by_client_certificate( + self, scopes: Iterable[str], certificate: AadClientCertificate, **kwargs + ) -> AccessToken: + request = self._get_client_certificate_request(scopes, certificate, **kwargs) + return await self._run_pipeline(request, stream=False, **kwargs) + + async def obtain_token_by_client_secret(self, scopes: Iterable[str], secret: str, **kwargs) -> AccessToken: + request = self._get_client_secret_request(scopes, secret, **kwargs) + return await self._run_pipeline(request, **kwargs) + + async def obtain_token_by_jwt_assertion(self, scopes: Iterable[str], assertion: str, **kwargs) -> AccessToken: + request = self._get_jwt_assertion_request(scopes, assertion, **kwargs) + return await self._run_pipeline(request, stream=False, **kwargs) + + async def obtain_token_by_refresh_token(self, scopes: Iterable[str], refresh_token: str, **kwargs) -> AccessToken: + request = self._get_refresh_token_request(scopes, refresh_token, **kwargs) + return await self._run_pipeline(request, **kwargs) + + async def obtain_token_by_refresh_token_on_behalf_of( # pylint: disable=name-too-long + self, scopes: Iterable[str], client_credential: Union[str, AadClientCertificate], refresh_token: str, **kwargs + ) -> AccessToken: + request = self._get_refresh_token_on_behalf_of_request( + scopes, client_credential=client_credential, refresh_token=refresh_token, **kwargs + ) + return await self._run_pipeline(request, **kwargs) + + async def obtain_token_on_behalf_of( + self, scopes: Iterable[str], client_credential: Union[str, AadClientCertificate], user_assertion: str, **kwargs + ) -> AccessToken: + request = self._get_on_behalf_of_request( + scopes=scopes, client_credential=client_credential, user_assertion=user_assertion, **kwargs + ) + return await self._run_pipeline(request, **kwargs) + + def _build_pipeline(self, **kwargs) -> AsyncPipeline: + return build_async_pipeline(**kwargs) + + async def _run_pipeline(self, request: HttpRequest, **kwargs) -> AccessToken: + # remove tenant_id and claims kwarg that could have been passed from credential's get_token method + # tenant_id is already part of `request` at this point + kwargs.pop("tenant_id", None) + kwargs.pop("claims", None) + enable_cae = kwargs.pop("enable_cae", False) + now = int(time.time()) + response = await self._pipeline.run(request, retry_on_methods=self._POST, **kwargs) + return self._process_response(response, now, enable_cae=enable_cae, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/decorators.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..671ebf448444836434ff655031579591d6f2c9b9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/decorators.py @@ -0,0 +1,73 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import logging +import json +import base64 + +from azure.core.exceptions import ClientAuthenticationError + +from ..._internal import within_credential_chain + +_LOGGER = logging.getLogger(__name__) + + +def log_get_token_async(fn): + @functools.wraps(fn) + async def wrapper(*args, **kwargs): + try: + token = await fn(*args, **kwargs) + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.INFO, "%s succeeded", fn.__qualname__ + ) + if _LOGGER.isEnabledFor(logging.DEBUG): + try: + base64_meta_data = token.token.split(".")[1].encode("utf-8") + b"==" + json_bytes = base64.decodebytes(base64_meta_data) + json_string = json_bytes.decode("utf-8") + json_dict = json.loads(json_string) + upn = json_dict.get("upn", "unavailableUpn") + log_string = ( + "[Authenticated account] Client ID: {}. Tenant ID: {}. User Principal Name: {}. " + "Object ID (user): {}".format(json_dict["appid"], json_dict["tid"], upn, json_dict["oid"]) + ) + _LOGGER.debug(log_string) + except Exception: # pylint: disable=broad-except + _LOGGER.debug("Fail to log the account information") + return token + except Exception as ex: # pylint: disable=broad-except + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.WARNING, + "%s failed: %s", + fn.__qualname__, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise + + return wrapper + + +def wrap_exceptions(fn): + """Prevents leaking exceptions defined outside azure-core by raising ClientAuthenticationError from them. + + :param fn: The function to wrap. + :type fn: ~typing.Callable + :return: The wrapped function. + :rtype: callable + """ + + @functools.wraps(fn) + async def wrapper(*args, **kwargs): + try: + result = await fn(*args, **kwargs) + return result + except ClientAuthenticationError: + raise + except Exception as ex: # pylint:disable=broad-except + auth_error = ClientAuthenticationError(message="Authentication failed: {}".format(ex)) + raise auth_error from ex + + return wrapper diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/get_token_mixin.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/get_token_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..162e6a51da5795a3b797f3692d41a13ade964552 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/get_token_mixin.py @@ -0,0 +1,108 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import logging +import time +from typing import Any, Optional + +from azure.core.credentials import AccessToken +from ..._constants import DEFAULT_REFRESH_OFFSET, DEFAULT_TOKEN_REFRESH_RETRY_DELAY +from ..._internal import within_credential_chain + +_LOGGER = logging.getLogger(__name__) + + +class GetTokenMixin(abc.ABC): + def __init__(self, *args, **kwargs) -> None: + self._last_request_time = 0 + + # https://github.com/python/mypy/issues/5887 + super(GetTokenMixin, self).__init__(*args, **kwargs) # type: ignore + + @abc.abstractmethod + async def _acquire_token_silently(self, *scopes: str, **kwargs) -> Optional[AccessToken]: + """Attempt to acquire an access token from a cache or by redeeming a refresh token. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + + :return: An access token with the desired scopes if successful; otherwise, None. + :rtype: ~azure.core.credentials.AccessToken or None + """ + + @abc.abstractmethod + async def _request_token(self, *scopes: str, **kwargs) -> AccessToken: + """Request an access token from the STS. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + """ + + def _should_refresh(self, token: AccessToken) -> bool: + now = int(time.time()) + if token.expires_on - now > DEFAULT_REFRESH_OFFSET: + return False + if now - self._last_request_time < DEFAULT_TOKEN_REFRESH_RETRY_DELAY: + return False + return True + + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/azure/active-directory/develop/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + if not scopes: + raise ValueError('"get_token" requires at least one scope') + + try: + token = await self._acquire_token_silently(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + if not token: + self._last_request_time = int(time.time()) + token = await self._request_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + elif self._should_refresh(token): + try: + self._last_request_time = int(time.time()) + token = await self._request_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + except Exception: # pylint:disable=broad-except + pass + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.INFO, + "%s.get_token succeeded", + self.__class__.__name__, + ) + return token + + except Exception as ex: + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.WARNING, + "%s.get_token failed: %s", + self.__class__.__name__, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/managed_identity_base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/managed_identity_base.py new file mode 100644 index 0000000000000000000000000000000000000000..22d5119e19bd781651a5ea98adc10162c1d11317 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/managed_identity_base.py @@ -0,0 +1,55 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +from typing import Any, cast, Optional + +from azure.core.credentials import AccessToken +from . import AsyncContextManager +from .get_token_mixin import GetTokenMixin +from .managed_identity_client import AsyncManagedIdentityClient +from ... import CredentialUnavailableError + + +class AsyncManagedIdentityBase(AsyncContextManager, GetTokenMixin): + """Base class for internal credentials using AsyncManagedIdentityClient""" + + def __init__(self, **kwargs) -> None: + super().__init__() + self._client = self.get_client(**kwargs) + + @abc.abstractmethod + def get_client(self, **kwargs) -> Optional[AsyncManagedIdentityClient]: + pass + + @abc.abstractmethod + def get_unavailable_message(self) -> str: + pass + + async def __aenter__(self): + if self._client: + await self._client.__aenter__() + return self + + async def __aexit__(self, *args): + if self._client: + await self._client.__aexit__(*args) + + async def close(self) -> None: + await self.__aexit__() + + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + if not self._client: + raise CredentialUnavailableError(message=self.get_unavailable_message()) + return await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + async def _acquire_token_silently(self, *scopes: str, **kwargs) -> Optional[AccessToken]: + # casting because mypy can't determine that these methods are called + # only by get_token, which raises when self._client is None + return cast(AsyncManagedIdentityClient, self._client).get_cached_token(*scopes) + + async def _request_token(self, *scopes: str, **kwargs) -> AccessToken: + return await cast(AsyncManagedIdentityClient, self._client).request_token(*scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/managed_identity_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/managed_identity_client.py new file mode 100644 index 0000000000000000000000000000000000000000..3cd65fc3fda7c9a6bce769871f9e95cf9417ab00 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/aio/_internal/managed_identity_client.py @@ -0,0 +1,37 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import time + + +from azure.core.credentials import AccessToken +from azure.core.pipeline import AsyncPipeline +from .._internal import AsyncContextManager +from ..._internal import _scopes_to_resource +from ..._internal.managed_identity_client import ManagedIdentityClientBase +from ..._internal.pipeline import build_async_pipeline + + +# pylint:disable=async-client-bad-name,missing-client-constructor-parameter-credential +class AsyncManagedIdentityClient(AsyncContextManager, ManagedIdentityClientBase): + async def __aenter__(self): + await self._pipeline.__aenter__() + return self + + async def close(self) -> None: + await self._pipeline.__aexit__() + + async def request_token(self, *scopes: str, **kwargs) -> AccessToken: + # pylint:disable=invalid-overridden-method + resource = _scopes_to_resource(*scopes) + request = self._request_factory(resource, self._identity_config) + kwargs.pop("tenant_id", None) + kwargs.pop("claims", None) + request_time = int(time.time()) + response = await self._pipeline.run(request, retry_on_methods=[request.method], **kwargs) + token = self._process_response(response, request_time) + return token + + def _build_pipeline(self, **kwargs) -> AsyncPipeline: + return build_async_pipeline(**kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e79b73f42275b409b898a7b027d53fcf2b86e334 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/__init__.py @@ -0,0 +1,69 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +from azure.core.pipeline.policies import HttpLoggingPolicy +from ._authentication import ( + ARMChallengeAuthenticationPolicy, + AuxiliaryAuthenticationPolicy, +) +from ._base import ARMAutoResourceProviderRegistrationPolicy +from ._authentication_async import ( + AsyncARMChallengeAuthenticationPolicy, + AsyncAuxiliaryAuthenticationPolicy, +) +from ._base_async import AsyncARMAutoResourceProviderRegistrationPolicy + + +class ARMHttpLoggingPolicy(HttpLoggingPolicy): + """HttpLoggingPolicy with ARM specific safe headers fopr loggers.""" + + DEFAULT_HEADERS_ALLOWLIST = HttpLoggingPolicy.DEFAULT_HEADERS_ALLOWLIST | set( + [ + # https://docs.microsoft.com/azure/azure-resource-manager/management/request-limits-and-throttling#remaining-requests + "x-ms-ratelimit-remaining-subscription-reads", + "x-ms-ratelimit-remaining-subscription-writes", + "x-ms-ratelimit-remaining-tenant-reads", + "x-ms-ratelimit-remaining-tenant-writes", + "x-ms-ratelimit-remaining-subscription-resource-requests", + "x-ms-ratelimit-remaining-subscription-resource-entities-read", + "x-ms-ratelimit-remaining-tenant-resource-requests", + "x-ms-ratelimit-remaining-tenant-resource-entities-read", + # https://docs.microsoft.com/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors#call-rate-informational-response-headers + "x-ms-ratelimit-remaining-resource", + "x-ms-request-charge", + ] + ) + + +__all__ = [ + "ARMAutoResourceProviderRegistrationPolicy", + "ARMChallengeAuthenticationPolicy", + "ARMHttpLoggingPolicy", + "AsyncARMAutoResourceProviderRegistrationPolicy", + "AsyncARMChallengeAuthenticationPolicy", + "AuxiliaryAuthenticationPolicy", + "AsyncAuxiliaryAuthenticationPolicy", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_authentication.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_authentication.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3fb9b40b21d4832bc450c2a276eb65c4b67e87 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_authentication.py @@ -0,0 +1,170 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import base64 +import time +from typing import Optional, TypeVar + +from azure.core.pipeline.policies import BearerTokenCredentialPolicy, SansIOHTTPPolicy +from azure.core.pipeline import PipelineRequest, PipelineResponse +from azure.core.exceptions import ServiceRequestError + + +HTTPRequestType = TypeVar("HTTPRequestType") +HTTPResponseType = TypeVar("HTTPResponseType") + + +class ARMChallengeAuthenticationPolicy(BearerTokenCredentialPolicy): + """Adds a bearer token Authorization header to requests. + + This policy internally handles Continuous Access Evaluation (CAE) challenges. When it can't complete a challenge, + it will return the 401 (unauthorized) response from ARM. + + :param ~azure.core.credentials.TokenCredential credential: credential for authorizing requests + :param str scopes: required authentication scopes + """ + + def on_challenge( + self, + request: PipelineRequest[HTTPRequestType], + response: PipelineResponse[HTTPRequestType, HTTPResponseType], + ) -> bool: + """Authorize request according to an ARM authentication challenge + + :param ~azure.core.pipeline.PipelineRequest request: the request which elicited an authentication challenge + :param ~azure.core.pipeline.PipelineResponse response: ARM's response + :returns: a bool indicating whether the policy should send the request + """ + + challenge = response.http_response.headers.get("WWW-Authenticate") + if challenge: + claims = _parse_claims_challenge(challenge) + if claims: + self.authorize_request(request, *self._scopes, claims=claims) + return True + + return False + + +# pylint:disable=too-few-public-methods +class _AuxiliaryAuthenticationPolicyBase: + """Adds auxiliary authorization token header to requests. + + :param ~azure.core.credentials.TokenCredential auxiliary_credentials: auxiliary credential for authorizing requests + :param str scopes: required authentication scopes + """ + + def __init__(self, auxiliary_credentials, *scopes, **kwargs): # pylint: disable=unused-argument + self._auxiliary_credentials = auxiliary_credentials + self._scopes = scopes + self._aux_tokens = None + + @staticmethod + def _enforce_https(request: PipelineRequest[HTTPRequestType]) -> None: + # move 'enforce_https' from options to context, so it persists + # across retries but isn't passed to transport implementation + option = request.context.options.pop("enforce_https", None) + + # True is the default setting; we needn't preserve an explicit opt in to the default behavior + if option is False: + request.context["enforce_https"] = option + + enforce_https = request.context.get("enforce_https", True) + if enforce_https and not request.http_request.url.lower().startswith("https"): + raise ServiceRequestError( + "Bearer token authentication is not permitted for non-TLS protected (non-https) URLs." + ) + + def _update_headers(self, headers): + """Updates the x-ms-authorization-auxiliary header with the auxiliary token. + + :param dict headers: The HTTP Request headers + """ + if self._aux_tokens: + headers["x-ms-authorization-auxiliary"] = ", ".join( + "Bearer {}".format(token.token) for token in self._aux_tokens + ) + + @property + def _need_new_aux_tokens(self): + if not self._aux_tokens: + return True + for token in self._aux_tokens: + if token.expires_on - time.time() < 300: + return True + return False + + +class AuxiliaryAuthenticationPolicy( + _AuxiliaryAuthenticationPolicyBase, + SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType], +): + def _get_auxiliary_tokens(self, *scopes, **kwargs): + if self._auxiliary_credentials: + return [cred.get_token(*scopes, **kwargs) for cred in self._auxiliary_credentials] + return None + + def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Called before the policy sends a request. + + The base implementation authorizes the request with an auxiliary authorization token. + + :param ~azure.core.pipeline.PipelineRequest request: the request + """ + self._enforce_https(request) + + if self._need_new_aux_tokens: + self._aux_tokens = self._get_auxiliary_tokens(*self._scopes) + + self._update_headers(request.http_request.headers) + + +def _parse_claims_challenge(challenge: str) -> Optional[str]: + """Parse the "claims" parameter from an authentication challenge + + Example challenge with claims: + Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token", + error_description="User session has been revoked", + claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0=" + + :return: the challenge's "claims" parameter or None, if it doesn't contain that parameter + """ + encoded_claims = None + for parameter in challenge.split(","): + if "claims=" in parameter: + if encoded_claims: + # multiple claims challenges, e.g. for cross-tenant auth, would require special handling + return None + encoded_claims = parameter[parameter.index("=") + 1 :].strip(" \"'") + + if not encoded_claims: + return None + + padding_needed = -len(encoded_claims) % 4 + try: + decoded_claims = base64.urlsafe_b64decode(encoded_claims + "=" * padding_needed).decode() + return decoded_claims + except Exception: # pylint:disable=broad-except + return None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_authentication_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_authentication_async.py new file mode 100644 index 0000000000000000000000000000000000000000..f99be38772d43528558ed6f013a2052847a01b9c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_authentication_async.py @@ -0,0 +1,145 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from typing import TypeVar, Awaitable, Optional +import inspect + +from azure.core.pipeline.policies import ( + AsyncBearerTokenCredentialPolicy, + AsyncHTTPPolicy, +) +from azure.core.pipeline import PipelineRequest, PipelineResponse + +from ._authentication import _parse_claims_challenge, _AuxiliaryAuthenticationPolicyBase + + +HTTPRequestType = TypeVar("HTTPRequestType") +AsyncHTTPResponseType = TypeVar("AsyncHTTPResponseType") + + +async def await_result(func, *args, **kwargs): + """If func returns an awaitable, await it.""" + result = func(*args, **kwargs) + if inspect.isawaitable(result): + return await result + return result + + +class AsyncARMChallengeAuthenticationPolicy(AsyncBearerTokenCredentialPolicy): + """Adds a bearer token Authorization header to requests. + + This policy internally handles Continuous Access Evaluation (CAE) challenges. When it can't complete a challenge, + it will return the 401 (unauthorized) response from ARM. + + :param ~azure.core.credentials.TokenCredential credential: credential for authorizing requests + :param str scopes: required authentication scopes + """ + + # pylint:disable=unused-argument + async def on_challenge( + self, + request: PipelineRequest[HTTPRequestType], + response: PipelineResponse[HTTPRequestType, AsyncHTTPResponseType], + ) -> bool: + """Authorize request according to an ARM authentication challenge + + :param ~azure.core.pipeline.PipelineRequest request: the request which elicited an authentication challenge + :param ~azure.core.pipeline.PipelineResponse response: the resource provider's response + :returns: a bool indicating whether the policy should send the request + """ + + challenge = response.http_response.headers.get("WWW-Authenticate") + claims = _parse_claims_challenge(challenge) + if claims: + await self.authorize_request(request, *self._scopes, claims=claims) + return True + + return False + + +class AsyncAuxiliaryAuthenticationPolicy( + _AuxiliaryAuthenticationPolicyBase, + AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType], +): + async def _get_auxiliary_tokens(self, *scopes, **kwargs): + if self._auxiliary_credentials: + return [await cred.get_token(*scopes, **kwargs) for cred in self._auxiliary_credentials] + return None + + async def on_request(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Called before the policy sends a request. + + The base implementation authorizes the request with an auxiliary authorization token. + + :param ~azure.core.pipeline.PipelineRequest request: the request + """ + self._enforce_https(request) + + if self._need_new_aux_tokens: + self._aux_tokens = await self._get_auxiliary_tokens(*self._scopes) + + self._update_headers(request.http_request.headers) + + def on_response( + self, + request: PipelineRequest[HTTPRequestType], + response: PipelineResponse[HTTPRequestType, AsyncHTTPResponseType], + ) -> Optional[Awaitable[None]]: + """Executed after the request comes back from the next policy. + + :param request: Request to be modified after returning from the policy. + :type request: ~azure.core.pipeline.PipelineRequest + :param response: Pipeline response object + :type response: ~azure.core.pipeline.PipelineResponse + """ + + def on_exception(self, request: PipelineRequest[HTTPRequestType]) -> None: + """Executed when an exception is raised while executing the next policy. + + This method is executed inside the exception handler. + + :param request: The Pipeline request object + :type request: ~azure.core.pipeline.PipelineRequest + """ + # pylint: disable=no-self-use,unused-argument + return + + async def send( + self, request: PipelineRequest[HTTPRequestType] + ) -> PipelineResponse[HTTPRequestType, AsyncHTTPResponseType]: + """Authorize request with a bearer token and send it to the next policy + + :param request: The pipeline request object + :type request: ~azure.core.pipeline.PipelineRequest + """ + await await_result(self.on_request, request) + try: + response = await self.next.send(request) + await await_result(self.on_response, request, response) + except Exception: # pylint:disable=broad-except + handled = await await_result(self.on_exception, request) + if not handled: + raise + return response diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_base.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..8f00b976a5668388403afd125e06ddff220ed9ac --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_base.py @@ -0,0 +1,109 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import json +import logging +import re +import time +import uuid + +from azure.core.pipeline import PipelineContext, PipelineRequest +from azure.core.pipeline.policies import HTTPPolicy +from azure.core.pipeline.transport import HttpRequest + + +_LOGGER = logging.getLogger(__name__) + + +class ARMAutoResourceProviderRegistrationPolicy(HTTPPolicy): + """Auto register an ARM resource provider if not done yet.""" + + def send(self, request): + # type: (PipelineRequest[HTTPRequestType], Any) -> PipelineResponse[HTTPRequestType, HTTPResponseType] + http_request = request.http_request + response = self.next.send(request) + if response.http_response.status_code == 409: + rp_name = self._check_rp_not_registered_err(response) + if rp_name: + url_prefix = self._extract_subscription_url(http_request.url) + if not self._register_rp(request, url_prefix, rp_name): + return response + # Change the 'x-ms-client-request-id' otherwise the Azure endpoint + # just returns the same 409 payload without looking at the actual query + if "x-ms-client-request-id" in http_request.headers: + http_request.headers["x-ms-client-request-id"] = str(uuid.uuid4()) + response = self.next.send(request) + return response + + @staticmethod + def _check_rp_not_registered_err(response): + try: + response = json.loads(response.http_response.text()) + if response["error"]["code"] == "MissingSubscriptionRegistration": + match = re.match(r".*'(.*)'", response["error"]["message"]) + return match.group(1) + except Exception: # pylint: disable=broad-except + pass + return None + + @staticmethod + def _extract_subscription_url(url): + """Extract the first part of the URL, just after subscription: + https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ + """ + match = re.match(r".*/subscriptions/[a-f0-9-]+/", url, re.IGNORECASE) + if not match: + raise ValueError("Unable to extract subscription ID from URL") + return match.group(0) + + @staticmethod + def _build_next_request(initial_request, method, url): + request = HttpRequest(method, url) + context = PipelineContext(initial_request.context.transport, **initial_request.context.options) + return PipelineRequest(request, context) + + def _register_rp(self, initial_request, url_prefix, rp_name): + """Synchronously register the RP is paremeter. + + Return False if we have a reason to believe this didn't work + """ + post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name) + get_url = "{}providers/{}?api-version=2016-02-01".format(url_prefix, rp_name) + _LOGGER.warning( + "Resource provider '%s' used by this operation is not " "registered. We are registering for you.", + rp_name, + ) + post_response = self.next.send(self._build_next_request(initial_request, "POST", post_url)) + if post_response.http_response.status_code != 200: + _LOGGER.warning("Registration failed. Please register manually.") + return False + + while True: + time.sleep(10) + get_response = self.next.send(self._build_next_request(initial_request, "GET", get_url)) + rp_info = json.loads(get_response.http_response.text()) + if rp_info["registrationState"] == "Registered": + _LOGGER.warning("Registration succeeded.") + return True diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_base_async.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_base_async.py new file mode 100644 index 0000000000000000000000000000000000000000..6208df12e5ff2f7eba555a4579764bfedbec130a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/policies/_base_async.py @@ -0,0 +1,81 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import asyncio +import json +import logging +import uuid + +from azure.core.pipeline import PipelineRequest +from azure.core.pipeline.policies import AsyncHTTPPolicy + +from . import ARMAutoResourceProviderRegistrationPolicy + +_LOGGER = logging.getLogger(__name__) + + +class AsyncARMAutoResourceProviderRegistrationPolicy(ARMAutoResourceProviderRegistrationPolicy, AsyncHTTPPolicy): + """Auto register an ARM resource provider if not done yet.""" + + async def send(self, request: PipelineRequest): # pylint: disable=invalid-overridden-method + http_request = request.http_request + response = await self.next.send(request) + if response.http_response.status_code == 409: + rp_name = self._check_rp_not_registered_err(response) + if rp_name: + url_prefix = self._extract_subscription_url(http_request.url) + register_rp_status = await self._async_register_rp(request, url_prefix, rp_name) + if not register_rp_status: + return response + # Change the 'x-ms-client-request-id' otherwise the Azure endpoint + # just returns the same 409 payload without looking at the actual query + if "x-ms-client-request-id" in http_request.headers: + http_request.headers["x-ms-client-request-id"] = str(uuid.uuid4()) + response = await self.next.send(request) + return response + + async def _async_register_rp(self, initial_request, url_prefix, rp_name): + """Synchronously register the RP is paremeter. + + Return False if we have a reason to believe this didn't work + """ + post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name) + get_url = "{}providers/{}?api-version=2016-02-01".format(url_prefix, rp_name) + _LOGGER.warning( + "Resource provider '%s' used by this operation is not " "registered. We are registering for you.", + rp_name, + ) + post_response = await self.next.send(self._build_next_request(initial_request, "POST", post_url)) + if post_response.http_response.status_code != 200: + _LOGGER.warning("Registration failed. Please register manually.") + return False + + while True: + await asyncio.sleep(10) + get_response = await self.next.send(self._build_next_request(initial_request, "GET", get_url)) + rp_info = json.loads(get_response.http_response.text()) + if rp_info["registrationState"] == "Registered": + _LOGGER.warning("Registration succeeded.") + return True diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/polling/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/polling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c36aaed14908f4d68f5aa6c477c67e20ead0c569 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/polling/__init__.py @@ -0,0 +1,25 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/polling/arm_polling.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/polling/arm_polling.py new file mode 100644 index 0000000000000000000000000000000000000000..0353a7d3d85cf1585a79925ad5b854f7da1e6663 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/polling/arm_polling.py @@ -0,0 +1,191 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +from enum import Enum +from typing import TYPE_CHECKING, Optional, Union + +from azure.core import CaseInsensitiveEnumMeta +from azure.core.polling.base_polling import ( + LongRunningOperation, + LROBasePolling, + OperationFailed, + BadResponse, + OperationResourcePolling, + LocationPolling, + StatusCheckPolling, + _as_json, + _is_empty, +) + +if TYPE_CHECKING: + from azure.core.pipeline import PipelineResponse + from azure.core.pipeline.transport import ( + HttpResponse, + AsyncHttpResponse, + HttpRequest, + ) + + ResponseType = Union[HttpResponse, AsyncHttpResponse] + PipelineResponseType = PipelineResponse[HttpRequest, ResponseType] + + +class _LroOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Known LRO options from Swagger.""" + + FINAL_STATE_VIA = "final-state-via" + + +class _FinalStateViaOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Possible final-state-via options.""" + + AZURE_ASYNC_OPERATION_FINAL_STATE = "azure-async-operation" + LOCATION_FINAL_STATE = "location" + + +class AzureAsyncOperationPolling(OperationResourcePolling): + """Implements a operation resource polling, typically from Azure-AsyncOperation.""" + + def __init__(self, lro_options=None): + super(AzureAsyncOperationPolling, self).__init__(operation_location_header="azure-asyncoperation") + + self._lro_options = lro_options or {} + + def get_final_get_url(self, pipeline_response): + # type: (PipelineResponseType) -> Optional[str] + """If a final GET is needed, returns the URL. + + :rtype: str + """ + if ( + self._lro_options.get(_LroOption.FINAL_STATE_VIA) == _FinalStateViaOption.AZURE_ASYNC_OPERATION_FINAL_STATE + and self._request.method == "POST" + ): + return None + return super(AzureAsyncOperationPolling, self).get_final_get_url(pipeline_response) + + +class BodyContentPolling(LongRunningOperation): + """Poll based on the body content. + + Implement a ARM resource poller (using provisioning state). + """ + + def __init__(self): + self._initial_response = None + + def can_poll(self, pipeline_response): + # type: (PipelineResponseType) -> bool + """Answer if this polling method could be used.""" + response = pipeline_response.http_response + return response.request.method in ["PUT", "PATCH"] + + def get_polling_url(self): + # type: () -> str + """Return the polling URL.""" + return self._initial_response.http_response.request.url + + def get_final_get_url(self, pipeline_response): + # type: (PipelineResponseType) -> Optional[str] + """If a final GET is needed, returns the URL. + + :rtype: str + """ + return None + + def set_initial_status(self, pipeline_response): + # type: (PipelineResponseType) -> str + """Process first response after initiating long running operation. + + :param azure.core.pipeline.PipelineResponse response: initial REST call response. + """ + self._initial_response = pipeline_response + response = pipeline_response.http_response + + if response.status_code == 202: + return "InProgress" + if response.status_code == 201: + status = self._get_provisioning_state(response) + return status or "InProgress" + if response.status_code == 200: + status = self._get_provisioning_state(response) + return status or "Succeeded" + if response.status_code == 204: + return "Succeeded" + + raise OperationFailed("Invalid status found") + + @staticmethod + def _get_provisioning_state(response): + # type: (ResponseType) -> Optional[str] + """Attempt to get provisioning state from resource. + + :param azure.core.pipeline.transport.HttpResponse response: latest REST call response. + :returns: Status if found, else 'None'. + """ + if _is_empty(response): + return None + body = _as_json(response) + return body.get("properties", {}).get("provisioningState") + + def get_status(self, pipeline_response): + # type: (PipelineResponseType) -> str + """Process the latest status update retrieved from the same URL as + the previous request. + + :param azure.core.pipeline.PipelineResponse response: latest REST call response. + :raises: BadResponse if status not 200 or 204. + """ + response = pipeline_response.http_response + if _is_empty(response): + raise BadResponse("The response from long running operation does not contain a body.") + + status = self._get_provisioning_state(response) + return status or "Succeeded" + + +class ARMPolling(LROBasePolling): + def __init__( + self, timeout=30, lro_algorithms=None, lro_options=None, path_format_arguments=None, **operation_config + ): + lro_algorithms = lro_algorithms or [ + AzureAsyncOperationPolling(lro_options=lro_options), + LocationPolling(), + BodyContentPolling(), + StatusCheckPolling(), + ] + super(ARMPolling, self).__init__( + timeout=timeout, + lro_algorithms=lro_algorithms, + lro_options=lro_options, + path_format_arguments=path_format_arguments, + **operation_config + ) + + +__all__ = [ + "AzureAsyncOperationPolling", + "BodyContentPolling", + "ARMPolling", +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/polling/async_arm_polling.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/polling/async_arm_polling.py new file mode 100644 index 0000000000000000000000000000000000000000..c79ea88df49dbe019ced10cb8fc786c29595a52d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/polling/async_arm_polling.py @@ -0,0 +1,36 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +from azure.core.polling.async_base_polling import AsyncLROBasePolling + +from .arm_polling import ARMPolling + + +class AsyncARMPolling(ARMPolling, AsyncLROBasePolling): + pass + + +__all__ = ["AsyncARMPolling"] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f61173da894dc2c6e501a3ce3109edbf26986a8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._maria_db_management_client import MariaDBManagementClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['MariaDBManagementClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..1504213dd71f887176ff880c2c2bf268cb4c9f7e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/_configuration.py @@ -0,0 +1,70 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import TokenCredential + + +class MariaDBManagementClientConfiguration(Configuration): + """Configuration for MariaDBManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(MariaDBManagementClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/_maria_db_management_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/_maria_db_management_client.py new file mode 100644 index 0000000000000000000000000000000000000000..ef2d7cd10911dad2b217951202fb2a5fb7d69d43 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/_maria_db_management_client.py @@ -0,0 +1,200 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.mgmt.core import ARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + + from azure.core.credentials import TokenCredential + from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from ._configuration import MariaDBManagementClientConfiguration +from .operations import ServersOperations +from .operations import ReplicasOperations +from .operations import FirewallRulesOperations +from .operations import VirtualNetworkRulesOperations +from .operations import DatabasesOperations +from .operations import ConfigurationsOperations +from .operations import ServerParametersOperations +from .operations import LogFilesOperations +from .operations import RecoverableServersOperations +from .operations import ServerBasedPerformanceTierOperations +from .operations import LocationBasedPerformanceTierOperations +from .operations import CheckNameAvailabilityOperations +from .operations import Operations +from .operations import QueryTextsOperations +from .operations import TopQueryStatisticsOperations +from .operations import WaitStatisticsOperations +from .operations import MariaDBManagementClientOperationsMixin +from .operations import AdvisorsOperations +from .operations import RecommendedActionsOperations +from .operations import LocationBasedRecommendedActionSessionsOperationStatusOperations +from .operations import LocationBasedRecommendedActionSessionsResultOperations +from .operations import PrivateEndpointConnectionsOperations +from .operations import PrivateLinkResourcesOperations +from .operations import ServerSecurityAlertPoliciesOperations +from . import models + + +class MariaDBManagementClient(MariaDBManagementClientOperationsMixin): + """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure MariaDB resources including servers, databases, firewall rules, VNET rules, log files and configurations with new business model. + + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.mariadb.operations.ServersOperations + :ivar replicas: ReplicasOperations operations + :vartype replicas: azure.mgmt.rdbms.mariadb.operations.ReplicasOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.rdbms.mariadb.operations.FirewallRulesOperations + :ivar virtual_network_rules: VirtualNetworkRulesOperations operations + :vartype virtual_network_rules: azure.mgmt.rdbms.mariadb.operations.VirtualNetworkRulesOperations + :ivar databases: DatabasesOperations operations + :vartype databases: azure.mgmt.rdbms.mariadb.operations.DatabasesOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: azure.mgmt.rdbms.mariadb.operations.ConfigurationsOperations + :ivar server_parameters: ServerParametersOperations operations + :vartype server_parameters: azure.mgmt.rdbms.mariadb.operations.ServerParametersOperations + :ivar log_files: LogFilesOperations operations + :vartype log_files: azure.mgmt.rdbms.mariadb.operations.LogFilesOperations + :ivar recoverable_servers: RecoverableServersOperations operations + :vartype recoverable_servers: azure.mgmt.rdbms.mariadb.operations.RecoverableServersOperations + :ivar server_based_performance_tier: ServerBasedPerformanceTierOperations operations + :vartype server_based_performance_tier: azure.mgmt.rdbms.mariadb.operations.ServerBasedPerformanceTierOperations + :ivar location_based_performance_tier: LocationBasedPerformanceTierOperations operations + :vartype location_based_performance_tier: azure.mgmt.rdbms.mariadb.operations.LocationBasedPerformanceTierOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: azure.mgmt.rdbms.mariadb.operations.CheckNameAvailabilityOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.mariadb.operations.Operations + :ivar query_texts: QueryTextsOperations operations + :vartype query_texts: azure.mgmt.rdbms.mariadb.operations.QueryTextsOperations + :ivar top_query_statistics: TopQueryStatisticsOperations operations + :vartype top_query_statistics: azure.mgmt.rdbms.mariadb.operations.TopQueryStatisticsOperations + :ivar wait_statistics: WaitStatisticsOperations operations + :vartype wait_statistics: azure.mgmt.rdbms.mariadb.operations.WaitStatisticsOperations + :ivar advisors: AdvisorsOperations operations + :vartype advisors: azure.mgmt.rdbms.mariadb.operations.AdvisorsOperations + :ivar recommended_actions: RecommendedActionsOperations operations + :vartype recommended_actions: azure.mgmt.rdbms.mariadb.operations.RecommendedActionsOperations + :ivar location_based_recommended_action_sessions_operation_status: LocationBasedRecommendedActionSessionsOperationStatusOperations operations + :vartype location_based_recommended_action_sessions_operation_status: azure.mgmt.rdbms.mariadb.operations.LocationBasedRecommendedActionSessionsOperationStatusOperations + :ivar location_based_recommended_action_sessions_result: LocationBasedRecommendedActionSessionsResultOperations operations + :vartype location_based_recommended_action_sessions_result: azure.mgmt.rdbms.mariadb.operations.LocationBasedRecommendedActionSessionsResultOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: azure.mgmt.rdbms.mariadb.operations.PrivateEndpointConnectionsOperations + :ivar private_link_resources: PrivateLinkResourcesOperations operations + :vartype private_link_resources: azure.mgmt.rdbms.mariadb.operations.PrivateLinkResourcesOperations + :ivar server_security_alert_policies: ServerSecurityAlertPoliciesOperations operations + :vartype server_security_alert_policies: azure.mgmt.rdbms.mariadb.operations.ServerSecurityAlertPoliciesOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + base_url=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> None + if not base_url: + base_url = 'https://management.azure.com' + self._config = MariaDBManagementClientConfiguration(credential, subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.servers = ServersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations( + self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.virtual_network_rules = VirtualNetworkRulesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_parameters = ServerParametersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.log_files = LogFilesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.recoverable_servers = RecoverableServersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_based_performance_tier = ServerBasedPerformanceTierOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_based_performance_tier = LocationBasedPerformanceTierOperations( + self._client, self._config, self._serialize, self._deserialize) + self.check_name_availability = CheckNameAvailabilityOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + self.query_texts = QueryTextsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.top_query_statistics = TopQueryStatisticsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.wait_statistics = WaitStatisticsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.advisors = AdvisorsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.recommended_actions = RecommendedActionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_based_recommended_action_sessions_operation_status = LocationBasedRecommendedActionSessionsOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_based_recommended_action_sessions_result = LocationBasedRecommendedActionSessionsResultOperations( + self._client, self._config, self._serialize, self._deserialize) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_security_alert_policies = ServerSecurityAlertPoliciesOperations( + self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, http_request, **kwargs): + # type: (HttpRequest, Any) -> HttpResponse + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.HttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> MariaDBManagementClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..c1257f7f4e111146dae88528000dc4841f2ef2aa --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "10.1.0" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1f9a1593b39d5c214d92c3f96198ef82985e9703 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._maria_db_management_client import MariaDBManagementClient +__all__ = ['MariaDBManagementClient'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..26c510686b11f2bbc224b0dc1f85d49f12b340c6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/_configuration.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class MariaDBManagementClientConfiguration(Configuration): + """Configuration for MariaDBManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(MariaDBManagementClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/_maria_db_management_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/_maria_db_management_client.py new file mode 100644 index 0000000000000000000000000000000000000000..d6370c9d2a64adac81a05c576a4d82032eb0e0aa --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/_maria_db_management_client.py @@ -0,0 +1,193 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +from ._configuration import MariaDBManagementClientConfiguration +from .operations import ServersOperations +from .operations import ReplicasOperations +from .operations import FirewallRulesOperations +from .operations import VirtualNetworkRulesOperations +from .operations import DatabasesOperations +from .operations import ConfigurationsOperations +from .operations import ServerParametersOperations +from .operations import LogFilesOperations +from .operations import RecoverableServersOperations +from .operations import ServerBasedPerformanceTierOperations +from .operations import LocationBasedPerformanceTierOperations +from .operations import CheckNameAvailabilityOperations +from .operations import Operations +from .operations import QueryTextsOperations +from .operations import TopQueryStatisticsOperations +from .operations import WaitStatisticsOperations +from .operations import MariaDBManagementClientOperationsMixin +from .operations import AdvisorsOperations +from .operations import RecommendedActionsOperations +from .operations import LocationBasedRecommendedActionSessionsOperationStatusOperations +from .operations import LocationBasedRecommendedActionSessionsResultOperations +from .operations import PrivateEndpointConnectionsOperations +from .operations import PrivateLinkResourcesOperations +from .operations import ServerSecurityAlertPoliciesOperations +from .. import models + + +class MariaDBManagementClient(MariaDBManagementClientOperationsMixin): + """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure MariaDB resources including servers, databases, firewall rules, VNET rules, log files and configurations with new business model. + + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.mariadb.aio.operations.ServersOperations + :ivar replicas: ReplicasOperations operations + :vartype replicas: azure.mgmt.rdbms.mariadb.aio.operations.ReplicasOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.rdbms.mariadb.aio.operations.FirewallRulesOperations + :ivar virtual_network_rules: VirtualNetworkRulesOperations operations + :vartype virtual_network_rules: azure.mgmt.rdbms.mariadb.aio.operations.VirtualNetworkRulesOperations + :ivar databases: DatabasesOperations operations + :vartype databases: azure.mgmt.rdbms.mariadb.aio.operations.DatabasesOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: azure.mgmt.rdbms.mariadb.aio.operations.ConfigurationsOperations + :ivar server_parameters: ServerParametersOperations operations + :vartype server_parameters: azure.mgmt.rdbms.mariadb.aio.operations.ServerParametersOperations + :ivar log_files: LogFilesOperations operations + :vartype log_files: azure.mgmt.rdbms.mariadb.aio.operations.LogFilesOperations + :ivar recoverable_servers: RecoverableServersOperations operations + :vartype recoverable_servers: azure.mgmt.rdbms.mariadb.aio.operations.RecoverableServersOperations + :ivar server_based_performance_tier: ServerBasedPerformanceTierOperations operations + :vartype server_based_performance_tier: azure.mgmt.rdbms.mariadb.aio.operations.ServerBasedPerformanceTierOperations + :ivar location_based_performance_tier: LocationBasedPerformanceTierOperations operations + :vartype location_based_performance_tier: azure.mgmt.rdbms.mariadb.aio.operations.LocationBasedPerformanceTierOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: azure.mgmt.rdbms.mariadb.aio.operations.CheckNameAvailabilityOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.mariadb.aio.operations.Operations + :ivar query_texts: QueryTextsOperations operations + :vartype query_texts: azure.mgmt.rdbms.mariadb.aio.operations.QueryTextsOperations + :ivar top_query_statistics: TopQueryStatisticsOperations operations + :vartype top_query_statistics: azure.mgmt.rdbms.mariadb.aio.operations.TopQueryStatisticsOperations + :ivar wait_statistics: WaitStatisticsOperations operations + :vartype wait_statistics: azure.mgmt.rdbms.mariadb.aio.operations.WaitStatisticsOperations + :ivar advisors: AdvisorsOperations operations + :vartype advisors: azure.mgmt.rdbms.mariadb.aio.operations.AdvisorsOperations + :ivar recommended_actions: RecommendedActionsOperations operations + :vartype recommended_actions: azure.mgmt.rdbms.mariadb.aio.operations.RecommendedActionsOperations + :ivar location_based_recommended_action_sessions_operation_status: LocationBasedRecommendedActionSessionsOperationStatusOperations operations + :vartype location_based_recommended_action_sessions_operation_status: azure.mgmt.rdbms.mariadb.aio.operations.LocationBasedRecommendedActionSessionsOperationStatusOperations + :ivar location_based_recommended_action_sessions_result: LocationBasedRecommendedActionSessionsResultOperations operations + :vartype location_based_recommended_action_sessions_result: azure.mgmt.rdbms.mariadb.aio.operations.LocationBasedRecommendedActionSessionsResultOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: azure.mgmt.rdbms.mariadb.aio.operations.PrivateEndpointConnectionsOperations + :ivar private_link_resources: PrivateLinkResourcesOperations operations + :vartype private_link_resources: azure.mgmt.rdbms.mariadb.aio.operations.PrivateLinkResourcesOperations + :ivar server_security_alert_policies: ServerSecurityAlertPoliciesOperations operations + :vartype server_security_alert_policies: azure.mgmt.rdbms.mariadb.aio.operations.ServerSecurityAlertPoliciesOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + **kwargs: Any + ) -> None: + if not base_url: + base_url = 'https://management.azure.com' + self._config = MariaDBManagementClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.servers = ServersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations( + self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.virtual_network_rules = VirtualNetworkRulesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_parameters = ServerParametersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.log_files = LogFilesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.recoverable_servers = RecoverableServersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_based_performance_tier = ServerBasedPerformanceTierOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_based_performance_tier = LocationBasedPerformanceTierOperations( + self._client, self._config, self._serialize, self._deserialize) + self.check_name_availability = CheckNameAvailabilityOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + self.query_texts = QueryTextsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.top_query_statistics = TopQueryStatisticsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.wait_statistics = WaitStatisticsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.advisors = AdvisorsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.recommended_actions = RecommendedActionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_based_recommended_action_sessions_operation_status = LocationBasedRecommendedActionSessionsOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_based_recommended_action_sessions_result = LocationBasedRecommendedActionSessionsResultOperations( + self._client, self._config, self._serialize, self._deserialize) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_security_alert_policies = ServerSecurityAlertPoliciesOperations( + self._client, self._config, self._serialize, self._deserialize) + + async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "MariaDBManagementClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..33ffedbabf7ff86392a81902b2c11c02533cb88c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/__init__.py @@ -0,0 +1,59 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._servers_operations import ServersOperations +from ._replicas_operations import ReplicasOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._virtual_network_rules_operations import VirtualNetworkRulesOperations +from ._databases_operations import DatabasesOperations +from ._configurations_operations import ConfigurationsOperations +from ._server_parameters_operations import ServerParametersOperations +from ._log_files_operations import LogFilesOperations +from ._recoverable_servers_operations import RecoverableServersOperations +from ._server_based_performance_tier_operations import ServerBasedPerformanceTierOperations +from ._location_based_performance_tier_operations import LocationBasedPerformanceTierOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._operations import Operations +from ._query_texts_operations import QueryTextsOperations +from ._top_query_statistics_operations import TopQueryStatisticsOperations +from ._wait_statistics_operations import WaitStatisticsOperations +from ._maria_db_management_client_operations import MariaDBManagementClientOperationsMixin +from ._advisors_operations import AdvisorsOperations +from ._recommended_actions_operations import RecommendedActionsOperations +from ._location_based_recommended_action_sessions_operation_status_operations import LocationBasedRecommendedActionSessionsOperationStatusOperations +from ._location_based_recommended_action_sessions_result_operations import LocationBasedRecommendedActionSessionsResultOperations +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._private_link_resources_operations import PrivateLinkResourcesOperations +from ._server_security_alert_policies_operations import ServerSecurityAlertPoliciesOperations + +__all__ = [ + 'ServersOperations', + 'ReplicasOperations', + 'FirewallRulesOperations', + 'VirtualNetworkRulesOperations', + 'DatabasesOperations', + 'ConfigurationsOperations', + 'ServerParametersOperations', + 'LogFilesOperations', + 'RecoverableServersOperations', + 'ServerBasedPerformanceTierOperations', + 'LocationBasedPerformanceTierOperations', + 'CheckNameAvailabilityOperations', + 'Operations', + 'QueryTextsOperations', + 'TopQueryStatisticsOperations', + 'WaitStatisticsOperations', + 'MariaDBManagementClientOperationsMixin', + 'AdvisorsOperations', + 'RecommendedActionsOperations', + 'LocationBasedRecommendedActionSessionsOperationStatusOperations', + 'LocationBasedRecommendedActionSessionsResultOperations', + 'PrivateEndpointConnectionsOperations', + 'PrivateLinkResourcesOperations', + 'ServerSecurityAlertPoliciesOperations', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_advisors_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_advisors_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b649899b8affe0ed14b6856ec0062def5d4a96e1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_advisors_operations.py @@ -0,0 +1,178 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class AdvisorsOperations: + """AdvisorsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + **kwargs: Any + ) -> "_models.Advisor": + """Get a recommendation action advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Advisor, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.Advisor + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Advisor"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'advisorName': self._serialize.url("advisor_name", advisor_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Advisor', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors/{advisorName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.AdvisorsResultList"]: + """List recommendation action advisors. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AdvisorsResultList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.AdvisorsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.AdvisorsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('AdvisorsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_check_name_availability_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_check_name_availability_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..0b53ce6f39e7249231a25285aa1535b69e3439af --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_check_name_availability_operations.py @@ -0,0 +1,100 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class CheckNameAvailabilityOperations: + """CheckNameAvailabilityOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def execute( + self, + name_availability_request: "_models.NameAvailabilityRequest", + **kwargs: Any + ) -> "_models.NameAvailability": + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. + :type name_availability_request: ~azure.mgmt.rdbms.mariadb.models.NameAvailabilityRequest + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.NameAvailability + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.execute.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('NameAvailability', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBForMariaDB/checkNameAvailability'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_configurations_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_configurations_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..95f31eeee3885f49eb4aa9f236afdbd4c2427627 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_configurations_operations.py @@ -0,0 +1,313 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ConfigurationsOperations: + """ConfigurationsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> Optional["_models.Configuration"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Configuration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> AsyncLROPoller["_models.Configuration"]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Configuration or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mariadb.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + **kwargs: Any + ) -> "_models.Configuration": + """Gets information about a configuration of server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Configuration, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.Configuration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ConfigurationListResult"]: + """List all the configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConfigurationListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/configurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_databases_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_databases_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..86f51286acd7e7dc73638924ea733f8c41dd361d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_databases_operations.py @@ -0,0 +1,431 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class DatabasesOperations: + """DatabasesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> Optional["_models.Database"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Database"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Database') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Database', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases/{databaseName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> AsyncLROPoller["_models.Database"]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.Database + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Database or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mariadb.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases/{databaseName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases/{databaseName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases/{databaseName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> "_models.Database": + """Gets information about a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Database, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.Database + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.DatabaseListResult"]: + """List all the databases in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DatabaseListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.DatabaseListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.DatabaseListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('DatabaseListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_firewall_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_firewall_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..7ed604a0b61c5ae69e064427e127c18e78c6914c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_firewall_rules_operations.py @@ -0,0 +1,431 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class FirewallRulesOperations: + """FirewallRulesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> Optional["_models.FirewallRule"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FirewallRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'FirewallRule') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> AsyncLROPoller["_models.FirewallRule"]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.FirewallRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either FirewallRule or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mariadb.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> "_models.FirewallRule": + """Gets information about a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FirewallRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.FirewallRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.FirewallRuleListResult"]: + """List all the firewall rules in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FirewallRuleListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.FirewallRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('FirewallRuleListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_location_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_location_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..5d08c93a18ccc09258b1f5b567c56e8c030090c3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_location_based_performance_tier_operations.py @@ -0,0 +1,112 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedPerformanceTierOperations: + """LocationBasedPerformanceTierOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + location_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PerformanceTierListResult"]: + """List all the performance tiers at specified location in a given subscription. + + :param location_name: The name of the location. + :type location_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('PerformanceTierListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBForMariaDB/locations/{locationName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_location_based_recommended_action_sessions_operation_status_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_location_based_recommended_action_sessions_operation_status_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b62f737c26b061ec975cf5f9b70ad50cd3c59859 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_location_based_recommended_action_sessions_operation_status_operations.py @@ -0,0 +1,99 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedRecommendedActionSessionsOperationStatusOperations: + """LocationBasedRecommendedActionSessionsOperationStatusOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + location_name: str, + operation_id: str, + **kwargs: Any + ) -> "_models.RecommendedActionSessionsOperationStatus": + """Recommendation action session operation status. + + :param location_name: The name of the location. + :type location_name: str + :param operation_id: The operation identifier. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecommendedActionSessionsOperationStatus, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.RecommendedActionSessionsOperationStatus + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendedActionSessionsOperationStatus"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + 'operationId': self._serialize.url("operation_id", operation_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecommendedActionSessionsOperationStatus', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMariaDB/locations/{locationName}/recommendedActionSessionsAzureAsyncOperation/{operationId}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_location_based_recommended_action_sessions_result_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_location_based_recommended_action_sessions_result_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..60ef8e8d8482b4643b205579076ec7b730288cde --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_location_based_recommended_action_sessions_result_operations.py @@ -0,0 +1,116 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedRecommendedActionSessionsResultOperations: + """LocationBasedRecommendedActionSessionsResultOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + location_name: str, + operation_id: str, + **kwargs: Any + ) -> AsyncIterable["_models.RecommendationActionsResultList"]: + """Recommendation action session operation result. + + :param location_name: The name of the location. + :type location_name: str + :param operation_id: The operation identifier. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RecommendationActionsResultList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.RecommendationActionsResultListor ~azure.mgmt.rdbms.mariadb.models.RecommendationActionsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationActionsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + 'operationId': self._serialize.url("operation_id", operation_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('RecommendationActionsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMariaDB/locations/{locationName}/recommendedActionSessionsOperationResults/{operationId}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_log_files_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_log_files_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b612b969d8ebb849035159ad1973e6b24d0a714b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_log_files_operations.py @@ -0,0 +1,116 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LogFilesOperations: + """LogFilesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.LogFileListResult"]: + """List all the log files in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either LogFileListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.LogFileListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.LogFileListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('LogFileListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/logFiles'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_maria_db_management_client_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_maria_db_management_client_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..c71be72d31323c7d377ae9f09de7d6eda767080a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_maria_db_management_client_operations.py @@ -0,0 +1,200 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class MariaDBManagementClientOperationsMixin: + + async def reset_query_performance_insight_data( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.QueryPerformanceInsightResetDataResult": + """Reset data for Query Performance Insight. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryPerformanceInsightResetDataResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.QueryPerformanceInsightResetDataResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryPerformanceInsightResetDataResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.reset_query_performance_insight_data.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryPerformanceInsightResetDataResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + reset_query_performance_insight_data.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/resetQueryPerformanceInsightData'} # type: ignore + + async def _create_recommended_action_session_initial( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + database_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + + # Construct URL + url = self._create_recommended_action_session_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'advisorName': self._serialize.url("advisor_name", advisor_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + query_parameters['databaseName'] = self._serialize.query("database_name", database_name, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _create_recommended_action_session_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession'} # type: ignore + + async def begin_create_recommended_action_session( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + database_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Create recommendation action session for the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_recommended_action_session_initial( + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'advisorName': self._serialize.url("advisor_name", advisor_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_recommended_action_session.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..2fa75451c42fc071b9adc8a7a44699df69a2233f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_operations.py @@ -0,0 +1,87 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class Operations: + """Operations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def list( + self, + **kwargs: Any + ) -> "_models.OperationListResult": + """Lists all of the available REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationListResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.OperationListResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.list.metadata['url'] # type: ignore + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + list.metadata = {'url': '/providers/Microsoft.DBForMariaDB/operations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_private_endpoint_connections_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_private_endpoint_connections_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..269395b56784a960d4996b063e53799890802bc6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_private_endpoint_connections_operations.py @@ -0,0 +1,562 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class PrivateEndpointConnectionsOperations: + """PrivateEndpointConnectionsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> "_models.PrivateEndpointConnection": + """Gets a private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnection + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.PrivateEndpointConnection", + **kwargs: Any + ) -> Optional["_models.PrivateEndpointConnection"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.PrivateEndpointConnection"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'PrivateEndpointConnection') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.PrivateEndpointConnection", + **kwargs: Any + ) -> AsyncLROPoller["_models.PrivateEndpointConnection"]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: + :type parameters: ~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnection + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def _update_tags_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.TagsObject", + **kwargs: Any + ) -> "_models.PrivateEndpointConnection": + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_tags_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'TagsObject') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_tags_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def begin_update_tags( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.TagsObject", + **kwargs: Any + ) -> AsyncLROPoller["_models.PrivateEndpointConnection"]: + """Updates tags on private endpoint connection. + + Updates private endpoint connection with the specified tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: Parameters supplied to the Update private endpoint connection Tags + operation. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.TagsObject + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._update_tags_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PrivateEndpointConnectionListResult"]: + """Gets all private endpoint connections on a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateEndpointConnectionListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnectionListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnectionListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_private_link_resources_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_private_link_resources_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..8f770dab87a2094835d2250505389cccf344e6f5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_private_link_resources_operations.py @@ -0,0 +1,178 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class PrivateLinkResourcesOperations: + """PrivateLinkResourcesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PrivateLinkResourceListResult"]: + """Gets the private link resources for MariaDB server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateLinkResourceListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.PrivateLinkResourceListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('PrivateLinkResourceListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateLinkResources'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + group_name: str, + **kwargs: Any + ) -> "_models.PrivateLinkResource": + """Gets a private link resource for MariaDB server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param group_name: The name of the private link resource. + :type group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateLinkResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.PrivateLinkResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'groupName': self._serialize.url("group_name", group_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateLinkResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateLinkResources/{groupName}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_query_texts_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_query_texts_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b10f2d804c4a4f2cbcef2a715a953ee4ab2d7deb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_query_texts_operations.py @@ -0,0 +1,182 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, List, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class QueryTextsOperations: + """QueryTextsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + query_id: str, + **kwargs: Any + ) -> "_models.QueryText": + """Retrieve the Query-Store query texts for the queryId. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_id: The Query-Store query identifier. + :type query_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryText, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.QueryText + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryText"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'queryId': self._serialize.url("query_id", query_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryText', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/queryTexts/{queryId}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + query_ids: List[str], + **kwargs: Any + ) -> AsyncIterable["_models.QueryTextsResultList"]: + """Retrieve the Query-Store query texts for specified queryIds. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_ids: The query identifiers. + :type query_ids: list[str] + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either QueryTextsResultList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.QueryTextsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryTextsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + query_parameters['queryIds'] = [self._serialize.query("query_ids", q, 'str') if q is not None else '' for q in query_ids] + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('QueryTextsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/queryTexts'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_recommended_actions_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_recommended_actions_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..5870001185a96d349bbe74d18c03632c2b92f009 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_recommended_actions_operations.py @@ -0,0 +1,191 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class RecommendedActionsOperations: + """RecommendedActionsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + recommended_action_name: str, + **kwargs: Any + ) -> "_models.RecommendationAction": + """Retrieve recommended actions from the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param recommended_action_name: The recommended action name. + :type recommended_action_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecommendationAction, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.RecommendationAction + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationAction"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'advisorName': self._serialize.url("advisor_name", advisor_name, 'str'), + 'recommendedActionName': self._serialize.url("recommended_action_name", recommended_action_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecommendationAction', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + session_id: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RecommendationActionsResultList"]: + """Retrieve recommended actions from the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param session_id: The recommendation action session identifier. + :type session_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RecommendationActionsResultList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.RecommendationActionsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationActionsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'advisorName': self._serialize.url("advisor_name", advisor_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + if session_id is not None: + query_parameters['sessionId'] = self._serialize.query("session_id", session_id, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('RecommendationActionsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors/{advisorName}/recommendedActions'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_recoverable_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_recoverable_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..182c81c5451c10beb35c89c6555e771e441811b5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_recoverable_servers_operations.py @@ -0,0 +1,99 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class RecoverableServersOperations: + """RecoverableServersOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.RecoverableServerResource": + """Gets a recoverable MariaDB Server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecoverableServerResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.RecoverableServerResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecoverableServerResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecoverableServerResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/recoverableServers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_replicas_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_replicas_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..dc96c75b1edf07493b5590ce9a930f317e10d60a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_replicas_operations.py @@ -0,0 +1,116 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ReplicasOperations: + """ReplicasOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the replicas for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/replicas'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_server_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_server_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b12eff8e8071e43867f35285f107a3019a0a30f8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_server_based_performance_tier_operations.py @@ -0,0 +1,116 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerBasedPerformanceTierOperations: + """ServerBasedPerformanceTierOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PerformanceTierListResult"]: + """List all the performance tiers for a MariaDB server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('PerformanceTierListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_server_parameters_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_server_parameters_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc184499de87c08a65b4e1afd7fe51df7865fe3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_server_parameters_operations.py @@ -0,0 +1,169 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerParametersOperations: + """ServerParametersOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _list_update_configurations_initial( + self, + resource_group_name: str, + server_name: str, + value: "_models.ConfigurationListResult", + **kwargs: Any + ) -> Optional["_models.ConfigurationListResult"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ConfigurationListResult"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._list_update_configurations_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(value, 'ConfigurationListResult') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _list_update_configurations_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/updateConfigurations'} # type: ignore + + async def begin_list_update_configurations( + self, + resource_group_name: str, + server_name: str, + value: "_models.ConfigurationListResult", + **kwargs: Any + ) -> AsyncLROPoller["_models.ConfigurationListResult"]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param value: The parameters for updating a list of server configuration. + :type value: ~azure.mgmt.rdbms.mariadb.models.ConfigurationListResult + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ConfigurationListResult or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mariadb.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._list_update_configurations_initial( + resource_group_name=resource_group_name, + server_name=server_name, + value=value, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_list_update_configurations.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/updateConfigurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_server_security_alert_policies_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_server_security_alert_policies_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..ad91d76675a7a454182321af59d90781bebdb5b6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_server_security_alert_policies_operations.py @@ -0,0 +1,313 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerSecurityAlertPoliciesOperations: + """ServerSecurityAlertPoliciesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + **kwargs: Any + ) -> "_models.ServerSecurityAlertPolicy": + """Get a server's security alert policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the security alert policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mariadb.models.SecurityAlertPolicyName + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerSecurityAlertPolicy, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicy + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + parameters: "_models.ServerSecurityAlertPolicy", + **kwargs: Any + ) -> Optional["_models.ServerSecurityAlertPolicy"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ServerSecurityAlertPolicy"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerSecurityAlertPolicy') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + parameters: "_models.ServerSecurityAlertPolicy", + **kwargs: Any + ) -> AsyncLROPoller["_models.ServerSecurityAlertPolicy"]: + """Creates or updates a threat detection policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the threat detection policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mariadb.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicy + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ServerSecurityAlertPolicy or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + security_alert_policy_name=security_alert_policy_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerSecurityAlertPolicyListResult"]: + """Get the server's threat detection policies. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerSecurityAlertPolicyListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicyListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicyListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerSecurityAlertPolicyListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/securityAlertPolicies'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b3371f81fee2844df9493f07a7129f2f309aacb3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_servers_operations.py @@ -0,0 +1,929 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServersOperations: + """ServersOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForCreate", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerForCreate') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + async def begin_create( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForCreate", + **kwargs: Any + ) -> AsyncLROPoller["_models.Server"]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.ServerForCreate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mariadb.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + async def _update_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpdateParameters", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerUpdateParameters') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + async def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpdateParameters", + **kwargs: Any + ) -> AsyncLROPoller["_models.Server"]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.ServerUpdateParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mariadb.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.Server": + """Gets information about a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Server, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.Server + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + def list_by_resource_group( + self, + resource_group_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the servers in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_resource_group.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers'} # type: ignore + + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the servers in a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBForMariaDB/servers'} # type: ignore + + async def _restart_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._restart_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/restart'} # type: ignore + + async def begin_restart( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._restart_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/restart'} # type: ignore + + async def _start_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + accept = "application/json" + + # Construct URL + url = self._start_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CloudErrorAutoGenerated, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/start'} # type: ignore + + async def begin_start( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Starts a stopped server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._start_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/start'} # type: ignore + + async def _stop_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + accept = "application/json" + + # Construct URL + url = self._stop_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CloudErrorAutoGenerated, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _stop_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/stop'} # type: ignore + + async def begin_stop( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Stops a running server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._stop_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/stop'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_top_query_statistics_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_top_query_statistics_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..112b66cd0f3d957aaf46637cf71ce46a1743b0c0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_top_query_statistics_operations.py @@ -0,0 +1,189 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class TopQueryStatisticsOperations: + """TopQueryStatisticsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + query_statistic_id: str, + **kwargs: Any + ) -> "_models.QueryStatistic": + """Retrieve the query statistic for specified identifier. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_statistic_id: The Query Statistic identifier. + :type query_statistic_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryStatistic, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.QueryStatistic + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryStatistic"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'queryStatisticId': self._serialize.url("query_statistic_id", query_statistic_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryStatistic', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/topQueryStatistics/{queryStatisticId}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.TopQueryStatisticsInput", + **kwargs: Any + ) -> AsyncIterable["_models.TopQueryStatisticsResultList"]: + """Retrieve the Query-Store top queries for specified metric and aggregation. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for retrieving top query statistics. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.TopQueryStatisticsInput + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either TopQueryStatisticsResultList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.TopQueryStatisticsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.TopQueryStatisticsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = "application/json" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'TopQueryStatisticsInput') + body_content_kwargs['content'] = body_content + request = self._client.get(url, query_parameters, header_parameters, **body_content_kwargs) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'TopQueryStatisticsInput') + body_content_kwargs['content'] = body_content + request = self._client.get(url, query_parameters, header_parameters, **body_content_kwargs) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('TopQueryStatisticsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/topQueryStatistics'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_virtual_network_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_virtual_network_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad782eef69812d07838e53a1bbb22530645caae --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_virtual_network_rules_operations.py @@ -0,0 +1,429 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class VirtualNetworkRulesOperations: + """VirtualNetworkRulesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> "_models.VirtualNetworkRule": + """Gets a virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: "_models.VirtualNetworkRule", + **kwargs: Any + ) -> Optional["_models.VirtualNetworkRule"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.VirtualNetworkRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'VirtualNetworkRule') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: "_models.VirtualNetworkRule", + **kwargs: Any + ) -> AsyncLROPoller["_models.VirtualNetworkRule"]: + """Creates or updates an existing virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :param parameters: The requested virtual Network Rule Resource state. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either VirtualNetworkRule or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the virtual network rule with the given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.VirtualNetworkRuleListResult"]: + """Gets a list of virtual network rules in a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either VirtualNetworkRuleListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('VirtualNetworkRuleListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_wait_statistics_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_wait_statistics_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..5d0053ac17de4b190659c9e251869484fc0f815e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/aio/operations/_wait_statistics_operations.py @@ -0,0 +1,189 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class WaitStatisticsOperations: + """WaitStatisticsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + wait_statistics_id: str, + **kwargs: Any + ) -> "_models.WaitStatistic": + """Retrieve wait statistics for specified identifier. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param wait_statistics_id: The Wait Statistic identifier. + :type wait_statistics_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: WaitStatistic, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.WaitStatistic + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.WaitStatistic"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'waitStatisticsId': self._serialize.url("wait_statistics_id", wait_statistics_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('WaitStatistic', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/waitStatistics/{waitStatisticsId}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.WaitStatisticsInput", + **kwargs: Any + ) -> AsyncIterable["_models.WaitStatisticsResultList"]: + """Retrieve wait statistics for specified aggregation window. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for retrieving wait statistics. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.WaitStatisticsInput + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either WaitStatisticsResultList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mariadb.models.WaitStatisticsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.WaitStatisticsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = "application/json" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'WaitStatisticsInput') + body_content_kwargs['content'] = body_content + request = self._client.get(url, query_parameters, header_parameters, **body_content_kwargs) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'WaitStatisticsInput') + body_content_kwargs['content'] = body_content + request = self._client.get(url, query_parameters, header_parameters, **body_content_kwargs) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('WaitStatisticsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/waitStatistics'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3b9745dc5250f611b36db7efecc99eac87678fed --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/__init__.py @@ -0,0 +1,239 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import Advisor + from ._models_py3 import AdvisorsResultList + from ._models_py3 import CloudErrorAutoGenerated + from ._models_py3 import Configuration + from ._models_py3 import ConfigurationListResult + from ._models_py3 import Database + from ._models_py3 import DatabaseListResult + from ._models_py3 import ErrorAdditionalInfo + from ._models_py3 import ErrorResponse + from ._models_py3 import FirewallRule + from ._models_py3 import FirewallRuleListResult + from ._models_py3 import LogFile + from ._models_py3 import LogFileListResult + from ._models_py3 import NameAvailability + from ._models_py3 import NameAvailabilityRequest + from ._models_py3 import Operation + from ._models_py3 import OperationDisplay + from ._models_py3 import OperationListResult + from ._models_py3 import PerformanceTierListResult + from ._models_py3 import PerformanceTierProperties + from ._models_py3 import PerformanceTierServiceLevelObjectives + from ._models_py3 import PrivateEndpointConnection + from ._models_py3 import PrivateEndpointConnectionListResult + from ._models_py3 import PrivateEndpointProperty + from ._models_py3 import PrivateLinkResource + from ._models_py3 import PrivateLinkResourceListResult + from ._models_py3 import PrivateLinkResourceProperties + from ._models_py3 import PrivateLinkServiceConnectionStateProperty + from ._models_py3 import ProxyResource + from ._models_py3 import QueryPerformanceInsightResetDataResult + from ._models_py3 import QueryStatistic + from ._models_py3 import QueryText + from ._models_py3 import QueryTextsResultList + from ._models_py3 import RecommendationAction + from ._models_py3 import RecommendationActionsResultList + from ._models_py3 import RecommendedActionSessionsOperationStatus + from ._models_py3 import RecoverableServerResource + from ._models_py3 import Resource + from ._models_py3 import Server + from ._models_py3 import ServerForCreate + from ._models_py3 import ServerListResult + from ._models_py3 import ServerPrivateEndpointConnection + from ._models_py3 import ServerPrivateEndpointConnectionProperties + from ._models_py3 import ServerPrivateLinkServiceConnectionStateProperty + from ._models_py3 import ServerPropertiesForCreate + from ._models_py3 import ServerPropertiesForDefaultCreate + from ._models_py3 import ServerPropertiesForGeoRestore + from ._models_py3 import ServerPropertiesForReplica + from ._models_py3 import ServerPropertiesForRestore + from ._models_py3 import ServerSecurityAlertPolicy + from ._models_py3 import ServerSecurityAlertPolicyListResult + from ._models_py3 import ServerUpdateParameters + from ._models_py3 import Sku + from ._models_py3 import StorageProfile + from ._models_py3 import TagsObject + from ._models_py3 import TopQueryStatisticsInput + from ._models_py3 import TopQueryStatisticsResultList + from ._models_py3 import TrackedResource + from ._models_py3 import VirtualNetworkRule + from ._models_py3 import VirtualNetworkRuleListResult + from ._models_py3 import WaitStatistic + from ._models_py3 import WaitStatisticsInput + from ._models_py3 import WaitStatisticsResultList +except (SyntaxError, ImportError): + from ._models import Advisor # type: ignore + from ._models import AdvisorsResultList # type: ignore + from ._models import CloudErrorAutoGenerated # type: ignore + from ._models import Configuration # type: ignore + from ._models import ConfigurationListResult # type: ignore + from ._models import Database # type: ignore + from ._models import DatabaseListResult # type: ignore + from ._models import ErrorAdditionalInfo # type: ignore + from ._models import ErrorResponse # type: ignore + from ._models import FirewallRule # type: ignore + from ._models import FirewallRuleListResult # type: ignore + from ._models import LogFile # type: ignore + from ._models import LogFileListResult # type: ignore + from ._models import NameAvailability # type: ignore + from ._models import NameAvailabilityRequest # type: ignore + from ._models import Operation # type: ignore + from ._models import OperationDisplay # type: ignore + from ._models import OperationListResult # type: ignore + from ._models import PerformanceTierListResult # type: ignore + from ._models import PerformanceTierProperties # type: ignore + from ._models import PerformanceTierServiceLevelObjectives # type: ignore + from ._models import PrivateEndpointConnection # type: ignore + from ._models import PrivateEndpointConnectionListResult # type: ignore + from ._models import PrivateEndpointProperty # type: ignore + from ._models import PrivateLinkResource # type: ignore + from ._models import PrivateLinkResourceListResult # type: ignore + from ._models import PrivateLinkResourceProperties # type: ignore + from ._models import PrivateLinkServiceConnectionStateProperty # type: ignore + from ._models import ProxyResource # type: ignore + from ._models import QueryPerformanceInsightResetDataResult # type: ignore + from ._models import QueryStatistic # type: ignore + from ._models import QueryText # type: ignore + from ._models import QueryTextsResultList # type: ignore + from ._models import RecommendationAction # type: ignore + from ._models import RecommendationActionsResultList # type: ignore + from ._models import RecommendedActionSessionsOperationStatus # type: ignore + from ._models import RecoverableServerResource # type: ignore + from ._models import Resource # type: ignore + from ._models import Server # type: ignore + from ._models import ServerForCreate # type: ignore + from ._models import ServerListResult # type: ignore + from ._models import ServerPrivateEndpointConnection # type: ignore + from ._models import ServerPrivateEndpointConnectionProperties # type: ignore + from ._models import ServerPrivateLinkServiceConnectionStateProperty # type: ignore + from ._models import ServerPropertiesForCreate # type: ignore + from ._models import ServerPropertiesForDefaultCreate # type: ignore + from ._models import ServerPropertiesForGeoRestore # type: ignore + from ._models import ServerPropertiesForReplica # type: ignore + from ._models import ServerPropertiesForRestore # type: ignore + from ._models import ServerSecurityAlertPolicy # type: ignore + from ._models import ServerSecurityAlertPolicyListResult # type: ignore + from ._models import ServerUpdateParameters # type: ignore + from ._models import Sku # type: ignore + from ._models import StorageProfile # type: ignore + from ._models import TagsObject # type: ignore + from ._models import TopQueryStatisticsInput # type: ignore + from ._models import TopQueryStatisticsResultList # type: ignore + from ._models import TrackedResource # type: ignore + from ._models import VirtualNetworkRule # type: ignore + from ._models import VirtualNetworkRuleListResult # type: ignore + from ._models import WaitStatistic # type: ignore + from ._models import WaitStatisticsInput # type: ignore + from ._models import WaitStatisticsResultList # type: ignore + +from ._maria_db_management_client_enums import ( + CreateMode, + GeoRedundantBackup, + MinimalTlsVersionEnum, + OperationOrigin, + PrivateEndpointProvisioningState, + PrivateLinkServiceConnectionStateActionsRequire, + PrivateLinkServiceConnectionStateStatus, + PublicNetworkAccessEnum, + QueryPerformanceInsightResetDataResultState, + SecurityAlertPolicyName, + ServerSecurityAlertPolicyState, + ServerState, + ServerVersion, + SkuTier, + SslEnforcementEnum, + StorageAutogrow, + VirtualNetworkRuleState, +) + +__all__ = [ + 'Advisor', + 'AdvisorsResultList', + 'CloudErrorAutoGenerated', + 'Configuration', + 'ConfigurationListResult', + 'Database', + 'DatabaseListResult', + 'ErrorAdditionalInfo', + 'ErrorResponse', + 'FirewallRule', + 'FirewallRuleListResult', + 'LogFile', + 'LogFileListResult', + 'NameAvailability', + 'NameAvailabilityRequest', + 'Operation', + 'OperationDisplay', + 'OperationListResult', + 'PerformanceTierListResult', + 'PerformanceTierProperties', + 'PerformanceTierServiceLevelObjectives', + 'PrivateEndpointConnection', + 'PrivateEndpointConnectionListResult', + 'PrivateEndpointProperty', + 'PrivateLinkResource', + 'PrivateLinkResourceListResult', + 'PrivateLinkResourceProperties', + 'PrivateLinkServiceConnectionStateProperty', + 'ProxyResource', + 'QueryPerformanceInsightResetDataResult', + 'QueryStatistic', + 'QueryText', + 'QueryTextsResultList', + 'RecommendationAction', + 'RecommendationActionsResultList', + 'RecommendedActionSessionsOperationStatus', + 'RecoverableServerResource', + 'Resource', + 'Server', + 'ServerForCreate', + 'ServerListResult', + 'ServerPrivateEndpointConnection', + 'ServerPrivateEndpointConnectionProperties', + 'ServerPrivateLinkServiceConnectionStateProperty', + 'ServerPropertiesForCreate', + 'ServerPropertiesForDefaultCreate', + 'ServerPropertiesForGeoRestore', + 'ServerPropertiesForReplica', + 'ServerPropertiesForRestore', + 'ServerSecurityAlertPolicy', + 'ServerSecurityAlertPolicyListResult', + 'ServerUpdateParameters', + 'Sku', + 'StorageProfile', + 'TagsObject', + 'TopQueryStatisticsInput', + 'TopQueryStatisticsResultList', + 'TrackedResource', + 'VirtualNetworkRule', + 'VirtualNetworkRuleListResult', + 'WaitStatistic', + 'WaitStatisticsInput', + 'WaitStatisticsResultList', + 'CreateMode', + 'GeoRedundantBackup', + 'MinimalTlsVersionEnum', + 'OperationOrigin', + 'PrivateEndpointProvisioningState', + 'PrivateLinkServiceConnectionStateActionsRequire', + 'PrivateLinkServiceConnectionStateStatus', + 'PublicNetworkAccessEnum', + 'QueryPerformanceInsightResetDataResultState', + 'SecurityAlertPolicyName', + 'ServerSecurityAlertPolicyState', + 'ServerState', + 'ServerVersion', + 'SkuTier', + 'SslEnforcementEnum', + 'StorageAutogrow', + 'VirtualNetworkRuleState', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/_maria_db_management_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/_maria_db_management_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..1328b53abf2dfa0e4e9ff7db3bcee0a7487e917e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/_maria_db_management_client_enums.py @@ -0,0 +1,158 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum, EnumMeta +from six import with_metaclass + +class _CaseInsensitiveEnumMeta(EnumMeta): + def __getitem__(self, name): + return super().__getitem__(name.upper()) + + def __getattr__(cls, name): + """Return the enum member matching `name` + We use __getattr__ instead of descriptors or inserting into the enum + class' __dict__ in order to support `name` and `value` being both + properties for enum members (which live in the class' __dict__) and + enum members themselves. + """ + try: + return cls._member_map_[name.upper()] + except KeyError: + raise AttributeError(name) + + +class CreateMode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The mode to create a new server. + """ + + DEFAULT = "Default" + POINT_IN_TIME_RESTORE = "PointInTimeRestore" + GEO_RESTORE = "GeoRestore" + REPLICA = "Replica" + +class GeoRedundantBackup(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Enable Geo-redundant or not for server backup. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class MinimalTlsVersionEnum(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Enforce a minimal Tls version for the server. + """ + + TLS1_0 = "TLS1_0" + TLS1_1 = "TLS1_1" + TLS1_2 = "TLS1_2" + TLS_ENFORCEMENT_DISABLED = "TLSEnforcementDisabled" + +class OperationOrigin(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The intended executor of the operation. + """ + + NOT_SPECIFIED = "NotSpecified" + USER = "user" + SYSTEM = "system" + +class PrivateEndpointProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """State of the private endpoint connection. + """ + + APPROVING = "Approving" + READY = "Ready" + DROPPING = "Dropping" + FAILED = "Failed" + REJECTING = "Rejecting" + +class PrivateLinkServiceConnectionStateActionsRequire(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The actions required for private link service connection. + """ + + NONE = "None" + +class PrivateLinkServiceConnectionStateStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The private link service connection status. + """ + + APPROVED = "Approved" + PENDING = "Pending" + REJECTED = "Rejected" + DISCONNECTED = "Disconnected" + +class PublicNetworkAccessEnum(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Whether or not public network access is allowed for this server. Value is optional but if + passed in, must be 'Enabled' or 'Disabled' + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class QueryPerformanceInsightResetDataResultState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Indicates result of the operation. + """ + + SUCCEEDED = "Succeeded" + FAILED = "Failed" + +class SecurityAlertPolicyName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + DEFAULT = "Default" + +class ServerSecurityAlertPolicyState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Specifies the state of the policy, whether it is enabled or disabled. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class ServerState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """A state of a server that is visible to user. + """ + + READY = "Ready" + DROPPING = "Dropping" + DISABLED = "Disabled" + +class ServerVersion(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The version of a server. + """ + + TEN2 = "10.2" + TEN3 = "10.3" + +class SkuTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The tier of the particular SKU, e.g. Basic. + """ + + BASIC = "Basic" + GENERAL_PURPOSE = "GeneralPurpose" + MEMORY_OPTIMIZED = "MemoryOptimized" + +class SslEnforcementEnum(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Enable ssl enforcement or not when connect to server. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class StorageAutogrow(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Enable Storage Auto Grow. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class VirtualNetworkRuleState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Virtual Network Rule State + """ + + INITIALIZING = "Initializing" + IN_PROGRESS = "InProgress" + READY = "Ready" + DELETING = "Deleting" + UNKNOWN = "Unknown" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/_models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f7142fc7a81e96aa9b93a5e0042331e5dc9ff2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/_models.py @@ -0,0 +1,2522 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + + +class Resource(msrest.serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class Advisor(ProxyResource): + """Represents a recommendation action advisor. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param properties: The properties of a recommendation action advisor. + :type properties: any + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + super(Advisor, self).__init__(**kwargs) + self.properties = kwargs.get('properties', None) + + +class AdvisorsResultList(msrest.serialization.Model): + """A list of query statistics. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of recommendation action advisors. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.Advisor] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Advisor]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(AdvisorsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class CloudErrorAutoGenerated(msrest.serialization.Model): + """An error response from the Batch service. + + :param error: Error message. + :type error: ~azure.mgmt.rdbms.mariadb.models.ErrorResponse + """ + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorResponse'}, + } + + def __init__( + self, + **kwargs + ): + super(CloudErrorAutoGenerated, self).__init__(**kwargs) + self.error = kwargs.get('error', None) + + +class Configuration(ProxyResource): + """Represents a Configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param value: Value of the configuration. + :type value: str + :ivar description: Description of the configuration. + :vartype description: str + :ivar default_value: Default value of the configuration. + :vartype default_value: str + :ivar data_type: Data type of the configuration. + :vartype data_type: str + :ivar allowed_values: Allowed values of the configuration. + :vartype allowed_values: str + :param source: Source of the configuration. + :type source: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'description': {'readonly': True}, + 'default_value': {'readonly': True}, + 'data_type': {'readonly': True}, + 'allowed_values': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'value': {'key': 'properties.value', 'type': 'str'}, + 'description': {'key': 'properties.description', 'type': 'str'}, + 'default_value': {'key': 'properties.defaultValue', 'type': 'str'}, + 'data_type': {'key': 'properties.dataType', 'type': 'str'}, + 'allowed_values': {'key': 'properties.allowedValues', 'type': 'str'}, + 'source': {'key': 'properties.source', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Configuration, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.description = None + self.default_value = None + self.data_type = None + self.allowed_values = None + self.source = kwargs.get('source', None) + + +class ConfigurationListResult(msrest.serialization.Model): + """A list of server configurations. + + :param value: The list of server configurations. + :type value: list[~azure.mgmt.rdbms.mariadb.models.Configuration] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Configuration]'}, + } + + def __init__( + self, + **kwargs + ): + super(ConfigurationListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class Database(ProxyResource): + """Represents a Database. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param charset: The charset of the database. + :type charset: str + :param collation: The collation of the database. + :type collation: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'charset': {'key': 'properties.charset', 'type': 'str'}, + 'collation': {'key': 'properties.collation', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Database, self).__init__(**kwargs) + self.charset = kwargs.get('charset', None) + self.collation = kwargs.get('collation', None) + + +class DatabaseListResult(msrest.serialization.Model): + """A List of databases. + + :param value: The list of databases housed in a server. + :type value: list[~azure.mgmt.rdbms.mariadb.models.Database] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Database]'}, + } + + def __init__( + self, + **kwargs + ): + super(DatabaseListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class ErrorAdditionalInfo(msrest.serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorResponse(msrest.serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.rdbms.mariadb.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.rdbms.mariadb.models.ErrorAdditionalInfo] + """ + + _validation = { + 'code': {'readonly': True}, + 'message': {'readonly': True}, + 'target': {'readonly': True}, + 'details': {'readonly': True}, + 'additional_info': {'readonly': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'target': {'key': 'target', 'type': 'str'}, + 'details': {'key': 'details', 'type': '[ErrorResponse]'}, + 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class FirewallRule(ProxyResource): + """Represents a server firewall rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param start_ip_address: Required. The start IP address of the server firewall rule. Must be + IPv4 format. + :type start_ip_address: str + :param end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 + format. + :type end_ip_address: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'start_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + 'end_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'start_ip_address': {'key': 'properties.startIpAddress', 'type': 'str'}, + 'end_ip_address': {'key': 'properties.endIpAddress', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FirewallRule, self).__init__(**kwargs) + self.start_ip_address = kwargs['start_ip_address'] + self.end_ip_address = kwargs['end_ip_address'] + + +class FirewallRuleListResult(msrest.serialization.Model): + """A list of firewall rules. + + :param value: The list of firewall rules in a server. + :type value: list[~azure.mgmt.rdbms.mariadb.models.FirewallRule] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FirewallRule]'}, + } + + def __init__( + self, + **kwargs + ): + super(FirewallRuleListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class LogFile(ProxyResource): + """Represents a log file. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param size_in_kb: Size of the log file. + :type size_in_kb: long + :ivar created_time: Creation timestamp of the log file. + :vartype created_time: ~datetime.datetime + :ivar last_modified_time: Last modified timestamp of the log file. + :vartype last_modified_time: ~datetime.datetime + :param type_properties_type: Type of the log file. + :type type_properties_type: str + :ivar url: The url to download the log file from. + :vartype url: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'created_time': {'readonly': True}, + 'last_modified_time': {'readonly': True}, + 'url': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'size_in_kb': {'key': 'properties.sizeInKB', 'type': 'long'}, + 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, + 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'iso-8601'}, + 'type_properties_type': {'key': 'properties.type', 'type': 'str'}, + 'url': {'key': 'properties.url', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(LogFile, self).__init__(**kwargs) + self.size_in_kb = kwargs.get('size_in_kb', None) + self.created_time = None + self.last_modified_time = None + self.type_properties_type = kwargs.get('type_properties_type', None) + self.url = None + + +class LogFileListResult(msrest.serialization.Model): + """A list of log files. + + :param value: The list of log files. + :type value: list[~azure.mgmt.rdbms.mariadb.models.LogFile] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[LogFile]'}, + } + + def __init__( + self, + **kwargs + ): + super(LogFileListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class NameAvailability(msrest.serialization.Model): + """Represents a resource name availability. + + :param message: Error Message. + :type message: str + :param name_available: Indicates whether the resource name is available. + :type name_available: bool + :param reason: Reason for name being unavailable. + :type reason: str + """ + + _attribute_map = { + 'message': {'key': 'message', 'type': 'str'}, + 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, + 'reason': {'key': 'reason', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(NameAvailability, self).__init__(**kwargs) + self.message = kwargs.get('message', None) + self.name_available = kwargs.get('name_available', None) + self.reason = kwargs.get('reason', None) + + +class NameAvailabilityRequest(msrest.serialization.Model): + """Request from client to check resource name availability. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. Resource name to verify. + :type name: str + :param type: Resource type used for verification. + :type type: str + """ + + _validation = { + 'name': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(NameAvailabilityRequest, self).__init__(**kwargs) + self.name = kwargs['name'] + self.type = kwargs.get('type', None) + + +class Operation(msrest.serialization.Model): + """REST API operation definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation being performed on this particular object. + :vartype name: str + :ivar display: The localized display information for this particular operation or action. + :vartype display: ~azure.mgmt.rdbms.mariadb.models.OperationDisplay + :ivar origin: The intended executor of the operation. Possible values include: "NotSpecified", + "user", "system". + :vartype origin: str or ~azure.mgmt.rdbms.mariadb.models.OperationOrigin + :ivar properties: Additional descriptions for the operation. + :vartype properties: dict[str, any] + """ + + _validation = { + 'name': {'readonly': True}, + 'display': {'readonly': True}, + 'origin': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'OperationDisplay'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{object}'}, + } + + def __init__( + self, + **kwargs + ): + super(Operation, self).__init__(**kwargs) + self.name = None + self.display = None + self.origin = None + self.properties = None + + +class OperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: Operation resource provider name. + :vartype provider: str + :ivar resource: Resource on which the operation is performed. + :vartype resource: str + :ivar operation: Localized friendly name for the operation. + :vartype operation: str + :ivar description: Operation description. + :vartype description: str + """ + + _validation = { + 'provider': {'readonly': True}, + 'resource': {'readonly': True}, + 'operation': {'readonly': True}, + 'description': {'readonly': True}, + } + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationDisplay, self).__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(msrest.serialization.Model): + """A list of resource provider operations. + + :param value: The list of resource provider operations. + :type value: list[~azure.mgmt.rdbms.mariadb.models.Operation] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Operation]'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class PerformanceTierListResult(msrest.serialization.Model): + """A list of performance tiers. + + :param value: The list of performance tiers. + :type value: list[~azure.mgmt.rdbms.mariadb.models.PerformanceTierProperties] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PerformanceTierProperties]'}, + } + + def __init__( + self, + **kwargs + ): + super(PerformanceTierListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class PerformanceTierProperties(msrest.serialization.Model): + """Performance tier properties. + + :param id: ID of the performance tier. + :type id: str + :param max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :type max_backup_retention_days: int + :param min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :type min_backup_retention_days: int + :param max_storage_mb: Max storage allowed for a server. + :type max_storage_mb: int + :param min_large_storage_mb: Max storage allowed for a server. + :type min_large_storage_mb: int + :param max_large_storage_mb: Max storage allowed for a server. + :type max_large_storage_mb: int + :param min_storage_mb: Max storage allowed for a server. + :type min_storage_mb: int + :param service_level_objectives: Service level objectives associated with the performance tier. + :type service_level_objectives: + list[~azure.mgmt.rdbms.mariadb.models.PerformanceTierServiceLevelObjectives] + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, + 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, + 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, + 'min_large_storage_mb': {'key': 'minLargeStorageMB', 'type': 'int'}, + 'max_large_storage_mb': {'key': 'maxLargeStorageMB', 'type': 'int'}, + 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, + 'service_level_objectives': {'key': 'serviceLevelObjectives', 'type': '[PerformanceTierServiceLevelObjectives]'}, + } + + def __init__( + self, + **kwargs + ): + super(PerformanceTierProperties, self).__init__(**kwargs) + self.id = kwargs.get('id', None) + self.max_backup_retention_days = kwargs.get('max_backup_retention_days', None) + self.min_backup_retention_days = kwargs.get('min_backup_retention_days', None) + self.max_storage_mb = kwargs.get('max_storage_mb', None) + self.min_large_storage_mb = kwargs.get('min_large_storage_mb', None) + self.max_large_storage_mb = kwargs.get('max_large_storage_mb', None) + self.min_storage_mb = kwargs.get('min_storage_mb', None) + self.service_level_objectives = kwargs.get('service_level_objectives', None) + + +class PerformanceTierServiceLevelObjectives(msrest.serialization.Model): + """Service level objectives for performance tier. + + :param id: ID for the service level objective. + :type id: str + :param edition: Edition of the performance tier. + :type edition: str + :param v_core: vCore associated with the service level objective. + :type v_core: int + :param hardware_generation: Hardware generation associated with the service level objective. + :type hardware_generation: str + :param max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :type max_backup_retention_days: int + :param min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :type min_backup_retention_days: int + :param max_storage_mb: Max storage allowed for a server. + :type max_storage_mb: int + :param min_storage_mb: Max storage allowed for a server. + :type min_storage_mb: int + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'edition': {'key': 'edition', 'type': 'str'}, + 'v_core': {'key': 'vCore', 'type': 'int'}, + 'hardware_generation': {'key': 'hardwareGeneration', 'type': 'str'}, + 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, + 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, + 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, + 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, + } + + def __init__( + self, + **kwargs + ): + super(PerformanceTierServiceLevelObjectives, self).__init__(**kwargs) + self.id = kwargs.get('id', None) + self.edition = kwargs.get('edition', None) + self.v_core = kwargs.get('v_core', None) + self.hardware_generation = kwargs.get('hardware_generation', None) + self.max_backup_retention_days = kwargs.get('max_backup_retention_days', None) + self.min_backup_retention_days = kwargs.get('min_backup_retention_days', None) + self.max_storage_mb = kwargs.get('max_storage_mb', None) + self.min_storage_mb = kwargs.get('min_storage_mb', None) + + +class PrivateEndpointConnection(ProxyResource): + """A private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param private_endpoint: Private endpoint which the connection belongs to. + :type private_endpoint: ~azure.mgmt.rdbms.mariadb.models.PrivateEndpointProperty + :param private_link_service_connection_state: Connection state of the private endpoint + connection. + :type private_link_service_connection_state: + ~azure.mgmt.rdbms.mariadb.models.PrivateLinkServiceConnectionStateProperty + :ivar provisioning_state: State of the private endpoint connection. + :vartype provisioning_state: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpointProperty'}, + 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionStateProperty'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateEndpointConnection, self).__init__(**kwargs) + self.private_endpoint = kwargs.get('private_endpoint', None) + self.private_link_service_connection_state = kwargs.get('private_link_service_connection_state', None) + self.provisioning_state = None + + +class PrivateEndpointConnectionListResult(msrest.serialization.Model): + """A list of private endpoint connections. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnection] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PrivateEndpointConnection]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateEndpointConnectionListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class PrivateEndpointProperty(msrest.serialization.Model): + """PrivateEndpointProperty. + + :param id: Resource id of the private endpoint. + :type id: str + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateEndpointProperty, self).__init__(**kwargs) + self.id = kwargs.get('id', None) + + +class PrivateLinkResource(ProxyResource): + """A private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar properties: The private link resource group id. + :vartype properties: ~azure.mgmt.rdbms.mariadb.models.PrivateLinkResourceProperties + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'PrivateLinkResourceProperties'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResource, self).__init__(**kwargs) + self.properties = None + + +class PrivateLinkResourceListResult(msrest.serialization.Model): + """A list of private link resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.PrivateLinkResource] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PrivateLinkResource]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResourceListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class PrivateLinkResourceProperties(msrest.serialization.Model): + """Properties of a private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar group_id: The private link resource group id. + :vartype group_id: str + :ivar required_members: The private link resource required member names. + :vartype required_members: list[str] + """ + + _validation = { + 'group_id': {'readonly': True}, + 'required_members': {'readonly': True}, + } + + _attribute_map = { + 'group_id': {'key': 'groupId', 'type': 'str'}, + 'required_members': {'key': 'requiredMembers', 'type': '[str]'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResourceProperties, self).__init__(**kwargs) + self.group_id = None + self.required_members = None + + +class PrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): + """PrivateLinkServiceConnectionStateProperty. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param status: Required. The private link service connection status. + :type status: str + :param description: Required. The private link service connection description. + :type description: str + :ivar actions_required: The actions required for private link service connection. + :vartype actions_required: str + """ + + _validation = { + 'status': {'required': True}, + 'description': {'required': True}, + 'actions_required': {'readonly': True}, + } + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + self.status = kwargs['status'] + self.description = kwargs['description'] + self.actions_required = None + + +class QueryPerformanceInsightResetDataResult(msrest.serialization.Model): + """Result of Query Performance Insight data reset. + + :param status: Indicates result of the operation. Possible values include: "Succeeded", + "Failed". + :type status: str or + ~azure.mgmt.rdbms.mariadb.models.QueryPerformanceInsightResetDataResultState + :param message: operation message. + :type message: str + """ + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(QueryPerformanceInsightResetDataResult, self).__init__(**kwargs) + self.status = kwargs.get('status', None) + self.message = kwargs.get('message', None) + + +class QueryStatistic(ProxyResource): + """Represents a Query Statistic. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param query_id: Database query identifier. + :type query_id: str + :param start_time: Observation start time. + :type start_time: ~datetime.datetime + :param end_time: Observation end time. + :type end_time: ~datetime.datetime + :param aggregation_function: Aggregation function name. + :type aggregation_function: str + :param database_names: The list of database names. + :type database_names: list[str] + :param query_execution_count: Number of query executions in this time interval. + :type query_execution_count: long + :param metric_name: Metric name. + :type metric_name: str + :param metric_display_name: Metric display name. + :type metric_display_name: str + :param metric_value: Metric value. + :type metric_value: float + :param metric_value_unit: Metric value unit. + :type metric_value_unit: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'query_id': {'key': 'properties.queryId', 'type': 'str'}, + 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, + 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, + 'aggregation_function': {'key': 'properties.aggregationFunction', 'type': 'str'}, + 'database_names': {'key': 'properties.databaseNames', 'type': '[str]'}, + 'query_execution_count': {'key': 'properties.queryExecutionCount', 'type': 'long'}, + 'metric_name': {'key': 'properties.metricName', 'type': 'str'}, + 'metric_display_name': {'key': 'properties.metricDisplayName', 'type': 'str'}, + 'metric_value': {'key': 'properties.metricValue', 'type': 'float'}, + 'metric_value_unit': {'key': 'properties.metricValueUnit', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(QueryStatistic, self).__init__(**kwargs) + self.query_id = kwargs.get('query_id', None) + self.start_time = kwargs.get('start_time', None) + self.end_time = kwargs.get('end_time', None) + self.aggregation_function = kwargs.get('aggregation_function', None) + self.database_names = kwargs.get('database_names', None) + self.query_execution_count = kwargs.get('query_execution_count', None) + self.metric_name = kwargs.get('metric_name', None) + self.metric_display_name = kwargs.get('metric_display_name', None) + self.metric_value = kwargs.get('metric_value', None) + self.metric_value_unit = kwargs.get('metric_value_unit', None) + + +class QueryText(ProxyResource): + """Represents a Query Text. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param query_id: Query identifier unique to the server. + :type query_id: str + :param query_text: Query text. + :type query_text: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'query_id': {'key': 'properties.queryId', 'type': 'str'}, + 'query_text': {'key': 'properties.queryText', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(QueryText, self).__init__(**kwargs) + self.query_id = kwargs.get('query_id', None) + self.query_text = kwargs.get('query_text', None) + + +class QueryTextsResultList(msrest.serialization.Model): + """A list of query texts. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of query texts. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.QueryText] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[QueryText]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(QueryTextsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class RecommendationAction(ProxyResource): + """Represents a Recommendation Action. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param advisor_name: Advisor name. + :type advisor_name: str + :param session_id: Recommendation action session identifier. + :type session_id: str + :param action_id: Recommendation action identifier. + :type action_id: int + :param created_time: Recommendation action creation time. + :type created_time: ~datetime.datetime + :param expiration_time: Recommendation action expiration time. + :type expiration_time: ~datetime.datetime + :param reason: Recommendation action reason. + :type reason: str + :param recommendation_type: Recommendation action type. + :type recommendation_type: str + :param details: Recommendation action details. + :type details: dict[str, str] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'advisor_name': {'key': 'properties.advisorName', 'type': 'str'}, + 'session_id': {'key': 'properties.sessionId', 'type': 'str'}, + 'action_id': {'key': 'properties.actionId', 'type': 'int'}, + 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, + 'expiration_time': {'key': 'properties.expirationTime', 'type': 'iso-8601'}, + 'reason': {'key': 'properties.reason', 'type': 'str'}, + 'recommendation_type': {'key': 'properties.recommendationType', 'type': 'str'}, + 'details': {'key': 'properties.details', 'type': '{str}'}, + } + + def __init__( + self, + **kwargs + ): + super(RecommendationAction, self).__init__(**kwargs) + self.advisor_name = kwargs.get('advisor_name', None) + self.session_id = kwargs.get('session_id', None) + self.action_id = kwargs.get('action_id', None) + self.created_time = kwargs.get('created_time', None) + self.expiration_time = kwargs.get('expiration_time', None) + self.reason = kwargs.get('reason', None) + self.recommendation_type = kwargs.get('recommendation_type', None) + self.details = kwargs.get('details', None) + + +class RecommendationActionsResultList(msrest.serialization.Model): + """A list of recommendation actions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of recommendation action advisors. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.RecommendationAction] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[RecommendationAction]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RecommendationActionsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class RecommendedActionSessionsOperationStatus(msrest.serialization.Model): + """Recommendation action session operation status. + + :param name: Operation identifier. + :type name: str + :param start_time: Operation start time. + :type start_time: ~datetime.datetime + :param status: Operation status. + :type status: str + """ + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RecommendedActionSessionsOperationStatus, self).__init__(**kwargs) + self.name = kwargs.get('name', None) + self.start_time = kwargs.get('start_time', None) + self.status = kwargs.get('status', None) + + +class RecoverableServerResource(ProxyResource): + """A recoverable server resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar last_available_backup_date_time: The last available backup date time. + :vartype last_available_backup_date_time: str + :ivar service_level_objective: The service level objective. + :vartype service_level_objective: str + :ivar edition: Edition of the performance tier. + :vartype edition: str + :ivar v_core: vCore associated with the service level objective. + :vartype v_core: int + :ivar hardware_generation: Hardware generation associated with the service level objective. + :vartype hardware_generation: str + :ivar version: The MariaDB version. + :vartype version: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'last_available_backup_date_time': {'readonly': True}, + 'service_level_objective': {'readonly': True}, + 'edition': {'readonly': True}, + 'v_core': {'readonly': True}, + 'hardware_generation': {'readonly': True}, + 'version': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'last_available_backup_date_time': {'key': 'properties.lastAvailableBackupDateTime', 'type': 'str'}, + 'service_level_objective': {'key': 'properties.serviceLevelObjective', 'type': 'str'}, + 'edition': {'key': 'properties.edition', 'type': 'str'}, + 'v_core': {'key': 'properties.vCore', 'type': 'int'}, + 'hardware_generation': {'key': 'properties.hardwareGeneration', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RecoverableServerResource, self).__init__(**kwargs) + self.last_available_backup_date_time = None + self.service_level_objective = None + self.edition = None + self.v_core = None + self.hardware_generation = None + self.version = None + + +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(TrackedResource, self).__init__(**kwargs) + self.tags = kwargs.get('tags', None) + self.location = kwargs['location'] + + +class Server(TrackedResource): + """Represents a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.mariadb.models.Sku + :param administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). + :type administrator_login: str + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param user_visible_state: A state of a server that is visible to user. Possible values + include: "Ready", "Dropping", "Disabled". + :type user_visible_state: str or ~azure.mgmt.rdbms.mariadb.models.ServerState + :param fully_qualified_domain_name: The fully qualified domain name of a server. + :type fully_qualified_domain_name: str + :param earliest_restore_date: Earliest restore point creation time (ISO8601 format). + :type earliest_restore_date: ~datetime.datetime + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param replication_role: The replication role of the server. + :type replication_role: str + :param master_server_id: The master server id of a replica server. + :type master_server_id: str + :param replica_capacity: The maximum number of replicas that a master server can have. + :type replica_capacity: int + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :ivar private_endpoint_connections: List of private endpoint connections on a server. + :vartype private_endpoint_connections: + list[~azure.mgmt.rdbms.mariadb.models.ServerPrivateEndpointConnection] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + 'replica_capacity': {'minimum': 0}, + 'private_endpoint_connections': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'administrator_login': {'key': 'properties.administratorLogin', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, + 'user_visible_state': {'key': 'properties.userVisibleState', 'type': 'str'}, + 'fully_qualified_domain_name': {'key': 'properties.fullyQualifiedDomainName', 'type': 'str'}, + 'earliest_restore_date': {'key': 'properties.earliestRestoreDate', 'type': 'iso-8601'}, + 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + 'master_server_id': {'key': 'properties.masterServerId', 'type': 'str'}, + 'replica_capacity': {'key': 'properties.replicaCapacity', 'type': 'int'}, + 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, + 'private_endpoint_connections': {'key': 'properties.privateEndpointConnections', 'type': '[ServerPrivateEndpointConnection]'}, + } + + def __init__( + self, + **kwargs + ): + super(Server, self).__init__(**kwargs) + self.sku = kwargs.get('sku', None) + self.administrator_login = kwargs.get('administrator_login', None) + self.version = kwargs.get('version', None) + self.ssl_enforcement = kwargs.get('ssl_enforcement', None) + self.minimal_tls_version = kwargs.get('minimal_tls_version', None) + self.user_visible_state = kwargs.get('user_visible_state', None) + self.fully_qualified_domain_name = kwargs.get('fully_qualified_domain_name', None) + self.earliest_restore_date = kwargs.get('earliest_restore_date', None) + self.storage_profile = kwargs.get('storage_profile', None) + self.replication_role = kwargs.get('replication_role', None) + self.master_server_id = kwargs.get('master_server_id', None) + self.replica_capacity = kwargs.get('replica_capacity', None) + self.public_network_access = kwargs.get('public_network_access', None) + self.private_endpoint_connections = None + + +class ServerForCreate(msrest.serialization.Model): + """Represents a server to be created. + + All required parameters must be populated in order to send to Azure. + + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.mariadb.models.Sku + :param properties: Required. Properties of the server. + :type properties: ~azure.mgmt.rdbms.mariadb.models.ServerPropertiesForCreate + :param location: Required. The location the resource resides in. + :type location: str + :param tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :type tags: dict[str, str] + """ + + _validation = { + 'properties': {'required': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'properties': {'key': 'properties', 'type': 'ServerPropertiesForCreate'}, + 'location': {'key': 'location', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerForCreate, self).__init__(**kwargs) + self.sku = kwargs.get('sku', None) + self.properties = kwargs['properties'] + self.location = kwargs['location'] + self.tags = kwargs.get('tags', None) + + +class ServerListResult(msrest.serialization.Model): + """A list of servers. + + :param value: The list of servers. + :type value: list[~azure.mgmt.rdbms.mariadb.models.Server] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Server]'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class ServerPrivateEndpointConnection(msrest.serialization.Model): + """A private endpoint connection under a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id of the private endpoint connection. + :vartype id: str + :ivar properties: Private endpoint connection properties. + :vartype properties: ~azure.mgmt.rdbms.mariadb.models.ServerPrivateEndpointConnectionProperties + """ + + _validation = { + 'id': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'ServerPrivateEndpointConnectionProperties'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPrivateEndpointConnection, self).__init__(**kwargs) + self.id = None + self.properties = None + + +class ServerPrivateEndpointConnectionProperties(msrest.serialization.Model): + """Properties of a private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param private_endpoint: Private endpoint which the connection belongs to. + :type private_endpoint: ~azure.mgmt.rdbms.mariadb.models.PrivateEndpointProperty + :param private_link_service_connection_state: Connection state of the private endpoint + connection. + :type private_link_service_connection_state: + ~azure.mgmt.rdbms.mariadb.models.ServerPrivateLinkServiceConnectionStateProperty + :ivar provisioning_state: State of the private endpoint connection. Possible values include: + "Approving", "Ready", "Dropping", "Failed", "Rejecting". + :vartype provisioning_state: str or + ~azure.mgmt.rdbms.mariadb.models.PrivateEndpointProvisioningState + """ + + _validation = { + 'provisioning_state': {'readonly': True}, + } + + _attribute_map = { + 'private_endpoint': {'key': 'privateEndpoint', 'type': 'PrivateEndpointProperty'}, + 'private_link_service_connection_state': {'key': 'privateLinkServiceConnectionState', 'type': 'ServerPrivateLinkServiceConnectionStateProperty'}, + 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPrivateEndpointConnectionProperties, self).__init__(**kwargs) + self.private_endpoint = kwargs.get('private_endpoint', None) + self.private_link_service_connection_state = kwargs.get('private_link_service_connection_state', None) + self.provisioning_state = None + + +class ServerPrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): + """ServerPrivateLinkServiceConnectionStateProperty. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param status: Required. The private link service connection status. Possible values include: + "Approved", "Pending", "Rejected", "Disconnected". + :type status: str or ~azure.mgmt.rdbms.mariadb.models.PrivateLinkServiceConnectionStateStatus + :param description: Required. The private link service connection description. + :type description: str + :ivar actions_required: The actions required for private link service connection. Possible + values include: "None". + :vartype actions_required: str or + ~azure.mgmt.rdbms.mariadb.models.PrivateLinkServiceConnectionStateActionsRequire + """ + + _validation = { + 'status': {'required': True}, + 'description': {'required': True}, + 'actions_required': {'readonly': True}, + } + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + self.status = kwargs['status'] + self.description = kwargs['description'] + self.actions_required = None + + +class ServerPropertiesForCreate(msrest.serialization.Model): + """The properties used to create a new server. + + You probably want to use the sub-classes and not this class directly. Known + sub-classes are: ServerPropertiesForDefaultCreate, ServerPropertiesForGeoRestore, ServerPropertiesForRestore, ServerPropertiesForReplica. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.mariadb.models.CreateMode + """ + + _validation = { + 'create_mode': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + } + + _subtype_map = { + 'create_mode': {'Default': 'ServerPropertiesForDefaultCreate', 'GeoRestore': 'ServerPropertiesForGeoRestore', 'PointInTimeRestore': 'ServerPropertiesForRestore', 'Replica': 'ServerPropertiesForReplica'} + } + + def __init__( + self, + **kwargs + ): + super(ServerPropertiesForCreate, self).__init__(**kwargs) + self.version = kwargs.get('version', None) + self.ssl_enforcement = kwargs.get('ssl_enforcement', None) + self.minimal_tls_version = kwargs.get('minimal_tls_version', None) + self.public_network_access = kwargs.get('public_network_access', None) + self.storage_profile = kwargs.get('storage_profile', None) + self.create_mode = None # type: Optional[str] + + +class ServerPropertiesForDefaultCreate(ServerPropertiesForCreate): + """The properties used to create a new server. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.mariadb.models.CreateMode + :param administrator_login: Required. The administrator's login name of a server. Can only be + specified when the server is being created (and is required for creation). + :type administrator_login: str + :param administrator_login_password: Required. The password of the administrator login. + :type administrator_login_password: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'administrator_login': {'required': True}, + 'administrator_login_password': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'administrator_login': {'key': 'administratorLogin', 'type': 'str'}, + 'administrator_login_password': {'key': 'administratorLoginPassword', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPropertiesForDefaultCreate, self).__init__(**kwargs) + self.create_mode = 'Default' # type: str + self.administrator_login = kwargs['administrator_login'] + self.administrator_login_password = kwargs['administrator_login_password'] + + +class ServerPropertiesForGeoRestore(ServerPropertiesForCreate): + """The properties used to create a new server by restoring to a different region from a geo replicated backup. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.mariadb.models.CreateMode + :param source_server_id: Required. The source server id to restore from. + :type source_server_id: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPropertiesForGeoRestore, self).__init__(**kwargs) + self.create_mode = 'GeoRestore' # type: str + self.source_server_id = kwargs['source_server_id'] + + +class ServerPropertiesForReplica(ServerPropertiesForCreate): + """The properties to create a new replica. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.mariadb.models.CreateMode + :param source_server_id: Required. The master server id to create replica from. + :type source_server_id: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPropertiesForReplica, self).__init__(**kwargs) + self.create_mode = 'Replica' # type: str + self.source_server_id = kwargs['source_server_id'] + + +class ServerPropertiesForRestore(ServerPropertiesForCreate): + """The properties used to create a new server by restoring from a backup. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.mariadb.models.CreateMode + :param source_server_id: Required. The source server id to restore from. + :type source_server_id: str + :param restore_point_in_time: Required. Restore point creation time (ISO8601 format), + specifying the time to restore from. + :type restore_point_in_time: ~datetime.datetime + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + 'restore_point_in_time': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + 'restore_point_in_time': {'key': 'restorePointInTime', 'type': 'iso-8601'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPropertiesForRestore, self).__init__(**kwargs) + self.create_mode = 'PointInTimeRestore' # type: str + self.source_server_id = kwargs['source_server_id'] + self.restore_point_in_time = kwargs['restore_point_in_time'] + + +class ServerSecurityAlertPolicy(ProxyResource): + """A server security alert policy. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param state: Specifies the state of the policy, whether it is enabled or disabled. Possible + values include: "Enabled", "Disabled". + :type state: str or ~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicyState + :param disabled_alerts: Specifies an array of alerts that are disabled. Allowed values are: + Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly. + :type disabled_alerts: list[str] + :param email_addresses: Specifies an array of e-mail addresses to which the alert is sent. + :type email_addresses: list[str] + :param email_account_admins: Specifies that the alert is sent to the account administrators. + :type email_account_admins: bool + :param storage_endpoint: Specifies the blob storage endpoint (e.g. + https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection + audit logs. + :type storage_endpoint: str + :param storage_account_access_key: Specifies the identifier key of the Threat Detection audit + storage account. + :type storage_account_access_key: str + :param retention_days: Specifies the number of days to keep in the Threat Detection audit logs. + :type retention_days: int + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + 'disabled_alerts': {'key': 'properties.disabledAlerts', 'type': '[str]'}, + 'email_addresses': {'key': 'properties.emailAddresses', 'type': '[str]'}, + 'email_account_admins': {'key': 'properties.emailAccountAdmins', 'type': 'bool'}, + 'storage_endpoint': {'key': 'properties.storageEndpoint', 'type': 'str'}, + 'storage_account_access_key': {'key': 'properties.storageAccountAccessKey', 'type': 'str'}, + 'retention_days': {'key': 'properties.retentionDays', 'type': 'int'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerSecurityAlertPolicy, self).__init__(**kwargs) + self.state = kwargs.get('state', None) + self.disabled_alerts = kwargs.get('disabled_alerts', None) + self.email_addresses = kwargs.get('email_addresses', None) + self.email_account_admins = kwargs.get('email_account_admins', None) + self.storage_endpoint = kwargs.get('storage_endpoint', None) + self.storage_account_access_key = kwargs.get('storage_account_access_key', None) + self.retention_days = kwargs.get('retention_days', None) + + +class ServerSecurityAlertPolicyListResult(msrest.serialization.Model): + """A list of the server's security alert policies. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicy] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerSecurityAlertPolicy]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerSecurityAlertPolicyListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ServerUpdateParameters(msrest.serialization.Model): + """Parameters allowed to update for a server. + + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.mariadb.models.Sku + :param tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :type tags: dict[str, str] + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param administrator_login_password: The password of the administrator login. + :type administrator_login_password: str + :param version: The version of a server. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param replication_role: The replication role of the server. + :type replication_role: str + """ + + _attribute_map = { + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, + 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerUpdateParameters, self).__init__(**kwargs) + self.sku = kwargs.get('sku', None) + self.tags = kwargs.get('tags', None) + self.storage_profile = kwargs.get('storage_profile', None) + self.administrator_login_password = kwargs.get('administrator_login_password', None) + self.version = kwargs.get('version', None) + self.ssl_enforcement = kwargs.get('ssl_enforcement', None) + self.minimal_tls_version = kwargs.get('minimal_tls_version', None) + self.public_network_access = kwargs.get('public_network_access', None) + self.replication_role = kwargs.get('replication_role', None) + + +class Sku(msrest.serialization.Model): + """Billing information related properties of a server. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, + GP_Gen5_8. + :type name: str + :param tier: The tier of the particular SKU, e.g. Basic. Possible values include: "Basic", + "GeneralPurpose", "MemoryOptimized". + :type tier: str or ~azure.mgmt.rdbms.mariadb.models.SkuTier + :param capacity: The scale up/out capacity, representing server's compute units. + :type capacity: int + :param size: The size code, to be interpreted by resource as appropriate. + :type size: str + :param family: The family of hardware. + :type family: str + """ + + _validation = { + 'name': {'required': True}, + 'capacity': {'minimum': 0}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'tier': {'key': 'tier', 'type': 'str'}, + 'capacity': {'key': 'capacity', 'type': 'int'}, + 'size': {'key': 'size', 'type': 'str'}, + 'family': {'key': 'family', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Sku, self).__init__(**kwargs) + self.name = kwargs['name'] + self.tier = kwargs.get('tier', None) + self.capacity = kwargs.get('capacity', None) + self.size = kwargs.get('size', None) + self.family = kwargs.get('family', None) + + +class StorageProfile(msrest.serialization.Model): + """Storage Profile properties of a server. + + :param backup_retention_days: Backup retention days for the server. + :type backup_retention_days: int + :param geo_redundant_backup: Enable Geo-redundant or not for server backup. Possible values + include: "Enabled", "Disabled". + :type geo_redundant_backup: str or ~azure.mgmt.rdbms.mariadb.models.GeoRedundantBackup + :param storage_mb: Max storage allowed for a server. + :type storage_mb: int + :param storage_autogrow: Enable Storage Auto Grow. Possible values include: "Enabled", + "Disabled". + :type storage_autogrow: str or ~azure.mgmt.rdbms.mariadb.models.StorageAutogrow + """ + + _attribute_map = { + 'backup_retention_days': {'key': 'backupRetentionDays', 'type': 'int'}, + 'geo_redundant_backup': {'key': 'geoRedundantBackup', 'type': 'str'}, + 'storage_mb': {'key': 'storageMB', 'type': 'int'}, + 'storage_autogrow': {'key': 'storageAutogrow', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(StorageProfile, self).__init__(**kwargs) + self.backup_retention_days = kwargs.get('backup_retention_days', None) + self.geo_redundant_backup = kwargs.get('geo_redundant_backup', None) + self.storage_mb = kwargs.get('storage_mb', None) + self.storage_autogrow = kwargs.get('storage_autogrow', None) + + +class TagsObject(msrest.serialization.Model): + """Tags object for patch operations. + + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + """ + + _attribute_map = { + 'tags': {'key': 'tags', 'type': '{str}'}, + } + + def __init__( + self, + **kwargs + ): + super(TagsObject, self).__init__(**kwargs) + self.tags = kwargs.get('tags', None) + + +class TopQueryStatisticsInput(msrest.serialization.Model): + """Input to get top query statistics. + + All required parameters must be populated in order to send to Azure. + + :param number_of_top_queries: Required. Max number of top queries to return. + :type number_of_top_queries: int + :param aggregation_function: Required. Aggregation function name. + :type aggregation_function: str + :param observed_metric: Required. Observed metric name. + :type observed_metric: str + :param observation_start_time: Required. Observation start time. + :type observation_start_time: ~datetime.datetime + :param observation_end_time: Required. Observation end time. + :type observation_end_time: ~datetime.datetime + :param aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :type aggregation_window: str + """ + + _validation = { + 'number_of_top_queries': {'required': True}, + 'aggregation_function': {'required': True}, + 'observed_metric': {'required': True}, + 'observation_start_time': {'required': True}, + 'observation_end_time': {'required': True}, + 'aggregation_window': {'required': True}, + } + + _attribute_map = { + 'number_of_top_queries': {'key': 'properties.numberOfTopQueries', 'type': 'int'}, + 'aggregation_function': {'key': 'properties.aggregationFunction', 'type': 'str'}, + 'observed_metric': {'key': 'properties.observedMetric', 'type': 'str'}, + 'observation_start_time': {'key': 'properties.observationStartTime', 'type': 'iso-8601'}, + 'observation_end_time': {'key': 'properties.observationEndTime', 'type': 'iso-8601'}, + 'aggregation_window': {'key': 'properties.aggregationWindow', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(TopQueryStatisticsInput, self).__init__(**kwargs) + self.number_of_top_queries = kwargs['number_of_top_queries'] + self.aggregation_function = kwargs['aggregation_function'] + self.observed_metric = kwargs['observed_metric'] + self.observation_start_time = kwargs['observation_start_time'] + self.observation_end_time = kwargs['observation_end_time'] + self.aggregation_window = kwargs['aggregation_window'] + + +class TopQueryStatisticsResultList(msrest.serialization.Model): + """A list of query statistics. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of top query statistics. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.QueryStatistic] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[QueryStatistic]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(TopQueryStatisticsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class VirtualNetworkRule(ProxyResource): + """A virtual network rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param virtual_network_subnet_id: The ARM resource id of the virtual network subnet. + :type virtual_network_subnet_id: str + :param ignore_missing_vnet_service_endpoint: Create firewall rule before the virtual network + has vnet service endpoint enabled. + :type ignore_missing_vnet_service_endpoint: bool + :ivar state: Virtual Network Rule State. Possible values include: "Initializing", "InProgress", + "Ready", "Deleting", "Unknown". + :vartype state: str or ~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRuleState + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'state': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'virtual_network_subnet_id': {'key': 'properties.virtualNetworkSubnetId', 'type': 'str'}, + 'ignore_missing_vnet_service_endpoint': {'key': 'properties.ignoreMissingVnetServiceEndpoint', 'type': 'bool'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(VirtualNetworkRule, self).__init__(**kwargs) + self.virtual_network_subnet_id = kwargs.get('virtual_network_subnet_id', None) + self.ignore_missing_vnet_service_endpoint = kwargs.get('ignore_missing_vnet_service_endpoint', None) + self.state = None + + +class VirtualNetworkRuleListResult(msrest.serialization.Model): + """A list of virtual network rules. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRule] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[VirtualNetworkRule]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(VirtualNetworkRuleListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class WaitStatistic(ProxyResource): + """Represents a Wait Statistic. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param start_time: Observation start time. + :type start_time: ~datetime.datetime + :param end_time: Observation end time. + :type end_time: ~datetime.datetime + :param event_name: Wait event name. + :type event_name: str + :param event_type_name: Wait event type name. + :type event_type_name: str + :param query_id: Database query identifier. + :type query_id: long + :param database_name: Database Name. + :type database_name: str + :param user_id: Database user identifier. + :type user_id: long + :param count: Wait event count observed in this time interval. + :type count: long + :param total_time_in_ms: Total time of wait in milliseconds in this time interval. + :type total_time_in_ms: float + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, + 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, + 'event_name': {'key': 'properties.eventName', 'type': 'str'}, + 'event_type_name': {'key': 'properties.eventTypeName', 'type': 'str'}, + 'query_id': {'key': 'properties.queryId', 'type': 'long'}, + 'database_name': {'key': 'properties.databaseName', 'type': 'str'}, + 'user_id': {'key': 'properties.userId', 'type': 'long'}, + 'count': {'key': 'properties.count', 'type': 'long'}, + 'total_time_in_ms': {'key': 'properties.totalTimeInMs', 'type': 'float'}, + } + + def __init__( + self, + **kwargs + ): + super(WaitStatistic, self).__init__(**kwargs) + self.start_time = kwargs.get('start_time', None) + self.end_time = kwargs.get('end_time', None) + self.event_name = kwargs.get('event_name', None) + self.event_type_name = kwargs.get('event_type_name', None) + self.query_id = kwargs.get('query_id', None) + self.database_name = kwargs.get('database_name', None) + self.user_id = kwargs.get('user_id', None) + self.count = kwargs.get('count', None) + self.total_time_in_ms = kwargs.get('total_time_in_ms', None) + + +class WaitStatisticsInput(msrest.serialization.Model): + """Input to get wait statistics. + + All required parameters must be populated in order to send to Azure. + + :param observation_start_time: Required. Observation start time. + :type observation_start_time: ~datetime.datetime + :param observation_end_time: Required. Observation end time. + :type observation_end_time: ~datetime.datetime + :param aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :type aggregation_window: str + """ + + _validation = { + 'observation_start_time': {'required': True}, + 'observation_end_time': {'required': True}, + 'aggregation_window': {'required': True}, + } + + _attribute_map = { + 'observation_start_time': {'key': 'properties.observationStartTime', 'type': 'iso-8601'}, + 'observation_end_time': {'key': 'properties.observationEndTime', 'type': 'iso-8601'}, + 'aggregation_window': {'key': 'properties.aggregationWindow', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(WaitStatisticsInput, self).__init__(**kwargs) + self.observation_start_time = kwargs['observation_start_time'] + self.observation_end_time = kwargs['observation_end_time'] + self.aggregation_window = kwargs['aggregation_window'] + + +class WaitStatisticsResultList(msrest.serialization.Model): + """A list of wait statistics. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of wait statistics. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.WaitStatistic] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[WaitStatistic]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(WaitStatisticsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..0c8578f6d31cc6782d868343fe651335919ec5d9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/models/_models_py3.py @@ -0,0 +1,2741 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import Any, Dict, List, Optional, Union + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + +from ._maria_db_management_client_enums import * + + +class Resource(msrest.serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class Advisor(ProxyResource): + """Represents a recommendation action advisor. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param properties: The properties of a recommendation action advisor. + :type properties: any + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'object'}, + } + + def __init__( + self, + *, + properties: Optional[Any] = None, + **kwargs + ): + super(Advisor, self).__init__(**kwargs) + self.properties = properties + + +class AdvisorsResultList(msrest.serialization.Model): + """A list of query statistics. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of recommendation action advisors. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.Advisor] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Advisor]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(AdvisorsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class CloudErrorAutoGenerated(msrest.serialization.Model): + """An error response from the Batch service. + + :param error: Error message. + :type error: ~azure.mgmt.rdbms.mariadb.models.ErrorResponse + """ + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorResponse'}, + } + + def __init__( + self, + *, + error: Optional["ErrorResponse"] = None, + **kwargs + ): + super(CloudErrorAutoGenerated, self).__init__(**kwargs) + self.error = error + + +class Configuration(ProxyResource): + """Represents a Configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param value: Value of the configuration. + :type value: str + :ivar description: Description of the configuration. + :vartype description: str + :ivar default_value: Default value of the configuration. + :vartype default_value: str + :ivar data_type: Data type of the configuration. + :vartype data_type: str + :ivar allowed_values: Allowed values of the configuration. + :vartype allowed_values: str + :param source: Source of the configuration. + :type source: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'description': {'readonly': True}, + 'default_value': {'readonly': True}, + 'data_type': {'readonly': True}, + 'allowed_values': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'value': {'key': 'properties.value', 'type': 'str'}, + 'description': {'key': 'properties.description', 'type': 'str'}, + 'default_value': {'key': 'properties.defaultValue', 'type': 'str'}, + 'data_type': {'key': 'properties.dataType', 'type': 'str'}, + 'allowed_values': {'key': 'properties.allowedValues', 'type': 'str'}, + 'source': {'key': 'properties.source', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[str] = None, + source: Optional[str] = None, + **kwargs + ): + super(Configuration, self).__init__(**kwargs) + self.value = value + self.description = None + self.default_value = None + self.data_type = None + self.allowed_values = None + self.source = source + + +class ConfigurationListResult(msrest.serialization.Model): + """A list of server configurations. + + :param value: The list of server configurations. + :type value: list[~azure.mgmt.rdbms.mariadb.models.Configuration] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Configuration]'}, + } + + def __init__( + self, + *, + value: Optional[List["Configuration"]] = None, + **kwargs + ): + super(ConfigurationListResult, self).__init__(**kwargs) + self.value = value + + +class Database(ProxyResource): + """Represents a Database. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param charset: The charset of the database. + :type charset: str + :param collation: The collation of the database. + :type collation: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'charset': {'key': 'properties.charset', 'type': 'str'}, + 'collation': {'key': 'properties.collation', 'type': 'str'}, + } + + def __init__( + self, + *, + charset: Optional[str] = None, + collation: Optional[str] = None, + **kwargs + ): + super(Database, self).__init__(**kwargs) + self.charset = charset + self.collation = collation + + +class DatabaseListResult(msrest.serialization.Model): + """A List of databases. + + :param value: The list of databases housed in a server. + :type value: list[~azure.mgmt.rdbms.mariadb.models.Database] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Database]'}, + } + + def __init__( + self, + *, + value: Optional[List["Database"]] = None, + **kwargs + ): + super(DatabaseListResult, self).__init__(**kwargs) + self.value = value + + +class ErrorAdditionalInfo(msrest.serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorResponse(msrest.serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.rdbms.mariadb.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.rdbms.mariadb.models.ErrorAdditionalInfo] + """ + + _validation = { + 'code': {'readonly': True}, + 'message': {'readonly': True}, + 'target': {'readonly': True}, + 'details': {'readonly': True}, + 'additional_info': {'readonly': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'target': {'key': 'target', 'type': 'str'}, + 'details': {'key': 'details', 'type': '[ErrorResponse]'}, + 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class FirewallRule(ProxyResource): + """Represents a server firewall rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param start_ip_address: Required. The start IP address of the server firewall rule. Must be + IPv4 format. + :type start_ip_address: str + :param end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 + format. + :type end_ip_address: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'start_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + 'end_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'start_ip_address': {'key': 'properties.startIpAddress', 'type': 'str'}, + 'end_ip_address': {'key': 'properties.endIpAddress', 'type': 'str'}, + } + + def __init__( + self, + *, + start_ip_address: str, + end_ip_address: str, + **kwargs + ): + super(FirewallRule, self).__init__(**kwargs) + self.start_ip_address = start_ip_address + self.end_ip_address = end_ip_address + + +class FirewallRuleListResult(msrest.serialization.Model): + """A list of firewall rules. + + :param value: The list of firewall rules in a server. + :type value: list[~azure.mgmt.rdbms.mariadb.models.FirewallRule] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FirewallRule]'}, + } + + def __init__( + self, + *, + value: Optional[List["FirewallRule"]] = None, + **kwargs + ): + super(FirewallRuleListResult, self).__init__(**kwargs) + self.value = value + + +class LogFile(ProxyResource): + """Represents a log file. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param size_in_kb: Size of the log file. + :type size_in_kb: long + :ivar created_time: Creation timestamp of the log file. + :vartype created_time: ~datetime.datetime + :ivar last_modified_time: Last modified timestamp of the log file. + :vartype last_modified_time: ~datetime.datetime + :param type_properties_type: Type of the log file. + :type type_properties_type: str + :ivar url: The url to download the log file from. + :vartype url: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'created_time': {'readonly': True}, + 'last_modified_time': {'readonly': True}, + 'url': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'size_in_kb': {'key': 'properties.sizeInKB', 'type': 'long'}, + 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, + 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'iso-8601'}, + 'type_properties_type': {'key': 'properties.type', 'type': 'str'}, + 'url': {'key': 'properties.url', 'type': 'str'}, + } + + def __init__( + self, + *, + size_in_kb: Optional[int] = None, + type_properties_type: Optional[str] = None, + **kwargs + ): + super(LogFile, self).__init__(**kwargs) + self.size_in_kb = size_in_kb + self.created_time = None + self.last_modified_time = None + self.type_properties_type = type_properties_type + self.url = None + + +class LogFileListResult(msrest.serialization.Model): + """A list of log files. + + :param value: The list of log files. + :type value: list[~azure.mgmt.rdbms.mariadb.models.LogFile] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[LogFile]'}, + } + + def __init__( + self, + *, + value: Optional[List["LogFile"]] = None, + **kwargs + ): + super(LogFileListResult, self).__init__(**kwargs) + self.value = value + + +class NameAvailability(msrest.serialization.Model): + """Represents a resource name availability. + + :param message: Error Message. + :type message: str + :param name_available: Indicates whether the resource name is available. + :type name_available: bool + :param reason: Reason for name being unavailable. + :type reason: str + """ + + _attribute_map = { + 'message': {'key': 'message', 'type': 'str'}, + 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, + 'reason': {'key': 'reason', 'type': 'str'}, + } + + def __init__( + self, + *, + message: Optional[str] = None, + name_available: Optional[bool] = None, + reason: Optional[str] = None, + **kwargs + ): + super(NameAvailability, self).__init__(**kwargs) + self.message = message + self.name_available = name_available + self.reason = reason + + +class NameAvailabilityRequest(msrest.serialization.Model): + """Request from client to check resource name availability. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. Resource name to verify. + :type name: str + :param type: Resource type used for verification. + :type type: str + """ + + _validation = { + 'name': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + name: str, + type: Optional[str] = None, + **kwargs + ): + super(NameAvailabilityRequest, self).__init__(**kwargs) + self.name = name + self.type = type + + +class Operation(msrest.serialization.Model): + """REST API operation definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation being performed on this particular object. + :vartype name: str + :ivar display: The localized display information for this particular operation or action. + :vartype display: ~azure.mgmt.rdbms.mariadb.models.OperationDisplay + :ivar origin: The intended executor of the operation. Possible values include: "NotSpecified", + "user", "system". + :vartype origin: str or ~azure.mgmt.rdbms.mariadb.models.OperationOrigin + :ivar properties: Additional descriptions for the operation. + :vartype properties: dict[str, any] + """ + + _validation = { + 'name': {'readonly': True}, + 'display': {'readonly': True}, + 'origin': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'OperationDisplay'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{object}'}, + } + + def __init__( + self, + **kwargs + ): + super(Operation, self).__init__(**kwargs) + self.name = None + self.display = None + self.origin = None + self.properties = None + + +class OperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: Operation resource provider name. + :vartype provider: str + :ivar resource: Resource on which the operation is performed. + :vartype resource: str + :ivar operation: Localized friendly name for the operation. + :vartype operation: str + :ivar description: Operation description. + :vartype description: str + """ + + _validation = { + 'provider': {'readonly': True}, + 'resource': {'readonly': True}, + 'operation': {'readonly': True}, + 'description': {'readonly': True}, + } + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationDisplay, self).__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(msrest.serialization.Model): + """A list of resource provider operations. + + :param value: The list of resource provider operations. + :type value: list[~azure.mgmt.rdbms.mariadb.models.Operation] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Operation]'}, + } + + def __init__( + self, + *, + value: Optional[List["Operation"]] = None, + **kwargs + ): + super(OperationListResult, self).__init__(**kwargs) + self.value = value + + +class PerformanceTierListResult(msrest.serialization.Model): + """A list of performance tiers. + + :param value: The list of performance tiers. + :type value: list[~azure.mgmt.rdbms.mariadb.models.PerformanceTierProperties] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PerformanceTierProperties]'}, + } + + def __init__( + self, + *, + value: Optional[List["PerformanceTierProperties"]] = None, + **kwargs + ): + super(PerformanceTierListResult, self).__init__(**kwargs) + self.value = value + + +class PerformanceTierProperties(msrest.serialization.Model): + """Performance tier properties. + + :param id: ID of the performance tier. + :type id: str + :param max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :type max_backup_retention_days: int + :param min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :type min_backup_retention_days: int + :param max_storage_mb: Max storage allowed for a server. + :type max_storage_mb: int + :param min_large_storage_mb: Max storage allowed for a server. + :type min_large_storage_mb: int + :param max_large_storage_mb: Max storage allowed for a server. + :type max_large_storage_mb: int + :param min_storage_mb: Max storage allowed for a server. + :type min_storage_mb: int + :param service_level_objectives: Service level objectives associated with the performance tier. + :type service_level_objectives: + list[~azure.mgmt.rdbms.mariadb.models.PerformanceTierServiceLevelObjectives] + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, + 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, + 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, + 'min_large_storage_mb': {'key': 'minLargeStorageMB', 'type': 'int'}, + 'max_large_storage_mb': {'key': 'maxLargeStorageMB', 'type': 'int'}, + 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, + 'service_level_objectives': {'key': 'serviceLevelObjectives', 'type': '[PerformanceTierServiceLevelObjectives]'}, + } + + def __init__( + self, + *, + id: Optional[str] = None, + max_backup_retention_days: Optional[int] = None, + min_backup_retention_days: Optional[int] = None, + max_storage_mb: Optional[int] = None, + min_large_storage_mb: Optional[int] = None, + max_large_storage_mb: Optional[int] = None, + min_storage_mb: Optional[int] = None, + service_level_objectives: Optional[List["PerformanceTierServiceLevelObjectives"]] = None, + **kwargs + ): + super(PerformanceTierProperties, self).__init__(**kwargs) + self.id = id + self.max_backup_retention_days = max_backup_retention_days + self.min_backup_retention_days = min_backup_retention_days + self.max_storage_mb = max_storage_mb + self.min_large_storage_mb = min_large_storage_mb + self.max_large_storage_mb = max_large_storage_mb + self.min_storage_mb = min_storage_mb + self.service_level_objectives = service_level_objectives + + +class PerformanceTierServiceLevelObjectives(msrest.serialization.Model): + """Service level objectives for performance tier. + + :param id: ID for the service level objective. + :type id: str + :param edition: Edition of the performance tier. + :type edition: str + :param v_core: vCore associated with the service level objective. + :type v_core: int + :param hardware_generation: Hardware generation associated with the service level objective. + :type hardware_generation: str + :param max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :type max_backup_retention_days: int + :param min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :type min_backup_retention_days: int + :param max_storage_mb: Max storage allowed for a server. + :type max_storage_mb: int + :param min_storage_mb: Max storage allowed for a server. + :type min_storage_mb: int + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'edition': {'key': 'edition', 'type': 'str'}, + 'v_core': {'key': 'vCore', 'type': 'int'}, + 'hardware_generation': {'key': 'hardwareGeneration', 'type': 'str'}, + 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, + 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, + 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, + 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, + } + + def __init__( + self, + *, + id: Optional[str] = None, + edition: Optional[str] = None, + v_core: Optional[int] = None, + hardware_generation: Optional[str] = None, + max_backup_retention_days: Optional[int] = None, + min_backup_retention_days: Optional[int] = None, + max_storage_mb: Optional[int] = None, + min_storage_mb: Optional[int] = None, + **kwargs + ): + super(PerformanceTierServiceLevelObjectives, self).__init__(**kwargs) + self.id = id + self.edition = edition + self.v_core = v_core + self.hardware_generation = hardware_generation + self.max_backup_retention_days = max_backup_retention_days + self.min_backup_retention_days = min_backup_retention_days + self.max_storage_mb = max_storage_mb + self.min_storage_mb = min_storage_mb + + +class PrivateEndpointConnection(ProxyResource): + """A private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param private_endpoint: Private endpoint which the connection belongs to. + :type private_endpoint: ~azure.mgmt.rdbms.mariadb.models.PrivateEndpointProperty + :param private_link_service_connection_state: Connection state of the private endpoint + connection. + :type private_link_service_connection_state: + ~azure.mgmt.rdbms.mariadb.models.PrivateLinkServiceConnectionStateProperty + :ivar provisioning_state: State of the private endpoint connection. + :vartype provisioning_state: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpointProperty'}, + 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionStateProperty'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + } + + def __init__( + self, + *, + private_endpoint: Optional["PrivateEndpointProperty"] = None, + private_link_service_connection_state: Optional["PrivateLinkServiceConnectionStateProperty"] = None, + **kwargs + ): + super(PrivateEndpointConnection, self).__init__(**kwargs) + self.private_endpoint = private_endpoint + self.private_link_service_connection_state = private_link_service_connection_state + self.provisioning_state = None + + +class PrivateEndpointConnectionListResult(msrest.serialization.Model): + """A list of private endpoint connections. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnection] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PrivateEndpointConnection]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateEndpointConnectionListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class PrivateEndpointProperty(msrest.serialization.Model): + """PrivateEndpointProperty. + + :param id: Resource id of the private endpoint. + :type id: str + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + } + + def __init__( + self, + *, + id: Optional[str] = None, + **kwargs + ): + super(PrivateEndpointProperty, self).__init__(**kwargs) + self.id = id + + +class PrivateLinkResource(ProxyResource): + """A private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar properties: The private link resource group id. + :vartype properties: ~azure.mgmt.rdbms.mariadb.models.PrivateLinkResourceProperties + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'PrivateLinkResourceProperties'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResource, self).__init__(**kwargs) + self.properties = None + + +class PrivateLinkResourceListResult(msrest.serialization.Model): + """A list of private link resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.PrivateLinkResource] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PrivateLinkResource]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResourceListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class PrivateLinkResourceProperties(msrest.serialization.Model): + """Properties of a private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar group_id: The private link resource group id. + :vartype group_id: str + :ivar required_members: The private link resource required member names. + :vartype required_members: list[str] + """ + + _validation = { + 'group_id': {'readonly': True}, + 'required_members': {'readonly': True}, + } + + _attribute_map = { + 'group_id': {'key': 'groupId', 'type': 'str'}, + 'required_members': {'key': 'requiredMembers', 'type': '[str]'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResourceProperties, self).__init__(**kwargs) + self.group_id = None + self.required_members = None + + +class PrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): + """PrivateLinkServiceConnectionStateProperty. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param status: Required. The private link service connection status. + :type status: str + :param description: Required. The private link service connection description. + :type description: str + :ivar actions_required: The actions required for private link service connection. + :vartype actions_required: str + """ + + _validation = { + 'status': {'required': True}, + 'description': {'required': True}, + 'actions_required': {'readonly': True}, + } + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + } + + def __init__( + self, + *, + status: str, + description: str, + **kwargs + ): + super(PrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + self.status = status + self.description = description + self.actions_required = None + + +class QueryPerformanceInsightResetDataResult(msrest.serialization.Model): + """Result of Query Performance Insight data reset. + + :param status: Indicates result of the operation. Possible values include: "Succeeded", + "Failed". + :type status: str or + ~azure.mgmt.rdbms.mariadb.models.QueryPerformanceInsightResetDataResultState + :param message: operation message. + :type message: str + """ + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__( + self, + *, + status: Optional[Union[str, "QueryPerformanceInsightResetDataResultState"]] = None, + message: Optional[str] = None, + **kwargs + ): + super(QueryPerformanceInsightResetDataResult, self).__init__(**kwargs) + self.status = status + self.message = message + + +class QueryStatistic(ProxyResource): + """Represents a Query Statistic. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param query_id: Database query identifier. + :type query_id: str + :param start_time: Observation start time. + :type start_time: ~datetime.datetime + :param end_time: Observation end time. + :type end_time: ~datetime.datetime + :param aggregation_function: Aggregation function name. + :type aggregation_function: str + :param database_names: The list of database names. + :type database_names: list[str] + :param query_execution_count: Number of query executions in this time interval. + :type query_execution_count: long + :param metric_name: Metric name. + :type metric_name: str + :param metric_display_name: Metric display name. + :type metric_display_name: str + :param metric_value: Metric value. + :type metric_value: float + :param metric_value_unit: Metric value unit. + :type metric_value_unit: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'query_id': {'key': 'properties.queryId', 'type': 'str'}, + 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, + 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, + 'aggregation_function': {'key': 'properties.aggregationFunction', 'type': 'str'}, + 'database_names': {'key': 'properties.databaseNames', 'type': '[str]'}, + 'query_execution_count': {'key': 'properties.queryExecutionCount', 'type': 'long'}, + 'metric_name': {'key': 'properties.metricName', 'type': 'str'}, + 'metric_display_name': {'key': 'properties.metricDisplayName', 'type': 'str'}, + 'metric_value': {'key': 'properties.metricValue', 'type': 'float'}, + 'metric_value_unit': {'key': 'properties.metricValueUnit', 'type': 'str'}, + } + + def __init__( + self, + *, + query_id: Optional[str] = None, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + aggregation_function: Optional[str] = None, + database_names: Optional[List[str]] = None, + query_execution_count: Optional[int] = None, + metric_name: Optional[str] = None, + metric_display_name: Optional[str] = None, + metric_value: Optional[float] = None, + metric_value_unit: Optional[str] = None, + **kwargs + ): + super(QueryStatistic, self).__init__(**kwargs) + self.query_id = query_id + self.start_time = start_time + self.end_time = end_time + self.aggregation_function = aggregation_function + self.database_names = database_names + self.query_execution_count = query_execution_count + self.metric_name = metric_name + self.metric_display_name = metric_display_name + self.metric_value = metric_value + self.metric_value_unit = metric_value_unit + + +class QueryText(ProxyResource): + """Represents a Query Text. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param query_id: Query identifier unique to the server. + :type query_id: str + :param query_text: Query text. + :type query_text: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'query_id': {'key': 'properties.queryId', 'type': 'str'}, + 'query_text': {'key': 'properties.queryText', 'type': 'str'}, + } + + def __init__( + self, + *, + query_id: Optional[str] = None, + query_text: Optional[str] = None, + **kwargs + ): + super(QueryText, self).__init__(**kwargs) + self.query_id = query_id + self.query_text = query_text + + +class QueryTextsResultList(msrest.serialization.Model): + """A list of query texts. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of query texts. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.QueryText] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[QueryText]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(QueryTextsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class RecommendationAction(ProxyResource): + """Represents a Recommendation Action. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param advisor_name: Advisor name. + :type advisor_name: str + :param session_id: Recommendation action session identifier. + :type session_id: str + :param action_id: Recommendation action identifier. + :type action_id: int + :param created_time: Recommendation action creation time. + :type created_time: ~datetime.datetime + :param expiration_time: Recommendation action expiration time. + :type expiration_time: ~datetime.datetime + :param reason: Recommendation action reason. + :type reason: str + :param recommendation_type: Recommendation action type. + :type recommendation_type: str + :param details: Recommendation action details. + :type details: dict[str, str] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'advisor_name': {'key': 'properties.advisorName', 'type': 'str'}, + 'session_id': {'key': 'properties.sessionId', 'type': 'str'}, + 'action_id': {'key': 'properties.actionId', 'type': 'int'}, + 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, + 'expiration_time': {'key': 'properties.expirationTime', 'type': 'iso-8601'}, + 'reason': {'key': 'properties.reason', 'type': 'str'}, + 'recommendation_type': {'key': 'properties.recommendationType', 'type': 'str'}, + 'details': {'key': 'properties.details', 'type': '{str}'}, + } + + def __init__( + self, + *, + advisor_name: Optional[str] = None, + session_id: Optional[str] = None, + action_id: Optional[int] = None, + created_time: Optional[datetime.datetime] = None, + expiration_time: Optional[datetime.datetime] = None, + reason: Optional[str] = None, + recommendation_type: Optional[str] = None, + details: Optional[Dict[str, str]] = None, + **kwargs + ): + super(RecommendationAction, self).__init__(**kwargs) + self.advisor_name = advisor_name + self.session_id = session_id + self.action_id = action_id + self.created_time = created_time + self.expiration_time = expiration_time + self.reason = reason + self.recommendation_type = recommendation_type + self.details = details + + +class RecommendationActionsResultList(msrest.serialization.Model): + """A list of recommendation actions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of recommendation action advisors. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.RecommendationAction] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[RecommendationAction]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RecommendationActionsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class RecommendedActionSessionsOperationStatus(msrest.serialization.Model): + """Recommendation action session operation status. + + :param name: Operation identifier. + :type name: str + :param start_time: Operation start time. + :type start_time: ~datetime.datetime + :param status: Operation status. + :type status: str + """ + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + start_time: Optional[datetime.datetime] = None, + status: Optional[str] = None, + **kwargs + ): + super(RecommendedActionSessionsOperationStatus, self).__init__(**kwargs) + self.name = name + self.start_time = start_time + self.status = status + + +class RecoverableServerResource(ProxyResource): + """A recoverable server resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar last_available_backup_date_time: The last available backup date time. + :vartype last_available_backup_date_time: str + :ivar service_level_objective: The service level objective. + :vartype service_level_objective: str + :ivar edition: Edition of the performance tier. + :vartype edition: str + :ivar v_core: vCore associated with the service level objective. + :vartype v_core: int + :ivar hardware_generation: Hardware generation associated with the service level objective. + :vartype hardware_generation: str + :ivar version: The MariaDB version. + :vartype version: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'last_available_backup_date_time': {'readonly': True}, + 'service_level_objective': {'readonly': True}, + 'edition': {'readonly': True}, + 'v_core': {'readonly': True}, + 'hardware_generation': {'readonly': True}, + 'version': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'last_available_backup_date_time': {'key': 'properties.lastAvailableBackupDateTime', 'type': 'str'}, + 'service_level_objective': {'key': 'properties.serviceLevelObjective', 'type': 'str'}, + 'edition': {'key': 'properties.edition', 'type': 'str'}, + 'v_core': {'key': 'properties.vCore', 'type': 'int'}, + 'hardware_generation': {'key': 'properties.hardwareGeneration', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RecoverableServerResource, self).__init__(**kwargs) + self.last_available_backup_date_time = None + self.service_level_objective = None + self.edition = None + self.v_core = None + self.hardware_generation = None + self.version = None + + +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + **kwargs + ): + super(TrackedResource, self).__init__(**kwargs) + self.tags = tags + self.location = location + + +class Server(TrackedResource): + """Represents a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.mariadb.models.Sku + :param administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). + :type administrator_login: str + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param user_visible_state: A state of a server that is visible to user. Possible values + include: "Ready", "Dropping", "Disabled". + :type user_visible_state: str or ~azure.mgmt.rdbms.mariadb.models.ServerState + :param fully_qualified_domain_name: The fully qualified domain name of a server. + :type fully_qualified_domain_name: str + :param earliest_restore_date: Earliest restore point creation time (ISO8601 format). + :type earliest_restore_date: ~datetime.datetime + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param replication_role: The replication role of the server. + :type replication_role: str + :param master_server_id: The master server id of a replica server. + :type master_server_id: str + :param replica_capacity: The maximum number of replicas that a master server can have. + :type replica_capacity: int + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :ivar private_endpoint_connections: List of private endpoint connections on a server. + :vartype private_endpoint_connections: + list[~azure.mgmt.rdbms.mariadb.models.ServerPrivateEndpointConnection] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + 'replica_capacity': {'minimum': 0}, + 'private_endpoint_connections': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'administrator_login': {'key': 'properties.administratorLogin', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, + 'user_visible_state': {'key': 'properties.userVisibleState', 'type': 'str'}, + 'fully_qualified_domain_name': {'key': 'properties.fullyQualifiedDomainName', 'type': 'str'}, + 'earliest_restore_date': {'key': 'properties.earliestRestoreDate', 'type': 'iso-8601'}, + 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + 'master_server_id': {'key': 'properties.masterServerId', 'type': 'str'}, + 'replica_capacity': {'key': 'properties.replicaCapacity', 'type': 'int'}, + 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, + 'private_endpoint_connections': {'key': 'properties.privateEndpointConnections', 'type': '[ServerPrivateEndpointConnection]'}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + sku: Optional["Sku"] = None, + administrator_login: Optional[str] = None, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + user_visible_state: Optional[Union[str, "ServerState"]] = None, + fully_qualified_domain_name: Optional[str] = None, + earliest_restore_date: Optional[datetime.datetime] = None, + storage_profile: Optional["StorageProfile"] = None, + replication_role: Optional[str] = None, + master_server_id: Optional[str] = None, + replica_capacity: Optional[int] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + **kwargs + ): + super(Server, self).__init__(tags=tags, location=location, **kwargs) + self.sku = sku + self.administrator_login = administrator_login + self.version = version + self.ssl_enforcement = ssl_enforcement + self.minimal_tls_version = minimal_tls_version + self.user_visible_state = user_visible_state + self.fully_qualified_domain_name = fully_qualified_domain_name + self.earliest_restore_date = earliest_restore_date + self.storage_profile = storage_profile + self.replication_role = replication_role + self.master_server_id = master_server_id + self.replica_capacity = replica_capacity + self.public_network_access = public_network_access + self.private_endpoint_connections = None + + +class ServerForCreate(msrest.serialization.Model): + """Represents a server to be created. + + All required parameters must be populated in order to send to Azure. + + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.mariadb.models.Sku + :param properties: Required. Properties of the server. + :type properties: ~azure.mgmt.rdbms.mariadb.models.ServerPropertiesForCreate + :param location: Required. The location the resource resides in. + :type location: str + :param tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :type tags: dict[str, str] + """ + + _validation = { + 'properties': {'required': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'properties': {'key': 'properties', 'type': 'ServerPropertiesForCreate'}, + 'location': {'key': 'location', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + } + + def __init__( + self, + *, + properties: "ServerPropertiesForCreate", + location: str, + sku: Optional["Sku"] = None, + tags: Optional[Dict[str, str]] = None, + **kwargs + ): + super(ServerForCreate, self).__init__(**kwargs) + self.sku = sku + self.properties = properties + self.location = location + self.tags = tags + + +class ServerListResult(msrest.serialization.Model): + """A list of servers. + + :param value: The list of servers. + :type value: list[~azure.mgmt.rdbms.mariadb.models.Server] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Server]'}, + } + + def __init__( + self, + *, + value: Optional[List["Server"]] = None, + **kwargs + ): + super(ServerListResult, self).__init__(**kwargs) + self.value = value + + +class ServerPrivateEndpointConnection(msrest.serialization.Model): + """A private endpoint connection under a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id of the private endpoint connection. + :vartype id: str + :ivar properties: Private endpoint connection properties. + :vartype properties: ~azure.mgmt.rdbms.mariadb.models.ServerPrivateEndpointConnectionProperties + """ + + _validation = { + 'id': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'ServerPrivateEndpointConnectionProperties'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPrivateEndpointConnection, self).__init__(**kwargs) + self.id = None + self.properties = None + + +class ServerPrivateEndpointConnectionProperties(msrest.serialization.Model): + """Properties of a private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param private_endpoint: Private endpoint which the connection belongs to. + :type private_endpoint: ~azure.mgmt.rdbms.mariadb.models.PrivateEndpointProperty + :param private_link_service_connection_state: Connection state of the private endpoint + connection. + :type private_link_service_connection_state: + ~azure.mgmt.rdbms.mariadb.models.ServerPrivateLinkServiceConnectionStateProperty + :ivar provisioning_state: State of the private endpoint connection. Possible values include: + "Approving", "Ready", "Dropping", "Failed", "Rejecting". + :vartype provisioning_state: str or + ~azure.mgmt.rdbms.mariadb.models.PrivateEndpointProvisioningState + """ + + _validation = { + 'provisioning_state': {'readonly': True}, + } + + _attribute_map = { + 'private_endpoint': {'key': 'privateEndpoint', 'type': 'PrivateEndpointProperty'}, + 'private_link_service_connection_state': {'key': 'privateLinkServiceConnectionState', 'type': 'ServerPrivateLinkServiceConnectionStateProperty'}, + 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, + } + + def __init__( + self, + *, + private_endpoint: Optional["PrivateEndpointProperty"] = None, + private_link_service_connection_state: Optional["ServerPrivateLinkServiceConnectionStateProperty"] = None, + **kwargs + ): + super(ServerPrivateEndpointConnectionProperties, self).__init__(**kwargs) + self.private_endpoint = private_endpoint + self.private_link_service_connection_state = private_link_service_connection_state + self.provisioning_state = None + + +class ServerPrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): + """ServerPrivateLinkServiceConnectionStateProperty. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param status: Required. The private link service connection status. Possible values include: + "Approved", "Pending", "Rejected", "Disconnected". + :type status: str or ~azure.mgmt.rdbms.mariadb.models.PrivateLinkServiceConnectionStateStatus + :param description: Required. The private link service connection description. + :type description: str + :ivar actions_required: The actions required for private link service connection. Possible + values include: "None". + :vartype actions_required: str or + ~azure.mgmt.rdbms.mariadb.models.PrivateLinkServiceConnectionStateActionsRequire + """ + + _validation = { + 'status': {'required': True}, + 'description': {'required': True}, + 'actions_required': {'readonly': True}, + } + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + } + + def __init__( + self, + *, + status: Union[str, "PrivateLinkServiceConnectionStateStatus"], + description: str, + **kwargs + ): + super(ServerPrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + self.status = status + self.description = description + self.actions_required = None + + +class ServerPropertiesForCreate(msrest.serialization.Model): + """The properties used to create a new server. + + You probably want to use the sub-classes and not this class directly. Known + sub-classes are: ServerPropertiesForDefaultCreate, ServerPropertiesForGeoRestore, ServerPropertiesForRestore, ServerPropertiesForReplica. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.mariadb.models.CreateMode + """ + + _validation = { + 'create_mode': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + } + + _subtype_map = { + 'create_mode': {'Default': 'ServerPropertiesForDefaultCreate', 'GeoRestore': 'ServerPropertiesForGeoRestore', 'PointInTimeRestore': 'ServerPropertiesForRestore', 'Replica': 'ServerPropertiesForReplica'} + } + + def __init__( + self, + *, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + super(ServerPropertiesForCreate, self).__init__(**kwargs) + self.version = version + self.ssl_enforcement = ssl_enforcement + self.minimal_tls_version = minimal_tls_version + self.public_network_access = public_network_access + self.storage_profile = storage_profile + self.create_mode = None # type: Optional[str] + + +class ServerPropertiesForDefaultCreate(ServerPropertiesForCreate): + """The properties used to create a new server. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.mariadb.models.CreateMode + :param administrator_login: Required. The administrator's login name of a server. Can only be + specified when the server is being created (and is required for creation). + :type administrator_login: str + :param administrator_login_password: Required. The password of the administrator login. + :type administrator_login_password: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'administrator_login': {'required': True}, + 'administrator_login_password': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'administrator_login': {'key': 'administratorLogin', 'type': 'str'}, + 'administrator_login_password': {'key': 'administratorLoginPassword', 'type': 'str'}, + } + + def __init__( + self, + *, + administrator_login: str, + administrator_login_password: str, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + super(ServerPropertiesForDefaultCreate, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'Default' # type: str + self.administrator_login = administrator_login + self.administrator_login_password = administrator_login_password + + +class ServerPropertiesForGeoRestore(ServerPropertiesForCreate): + """The properties used to create a new server by restoring to a different region from a geo replicated backup. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.mariadb.models.CreateMode + :param source_server_id: Required. The source server id to restore from. + :type source_server_id: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + } + + def __init__( + self, + *, + source_server_id: str, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + super(ServerPropertiesForGeoRestore, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'GeoRestore' # type: str + self.source_server_id = source_server_id + + +class ServerPropertiesForReplica(ServerPropertiesForCreate): + """The properties to create a new replica. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.mariadb.models.CreateMode + :param source_server_id: Required. The master server id to create replica from. + :type source_server_id: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + } + + def __init__( + self, + *, + source_server_id: str, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + super(ServerPropertiesForReplica, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'Replica' # type: str + self.source_server_id = source_server_id + + +class ServerPropertiesForRestore(ServerPropertiesForCreate): + """The properties used to create a new server by restoring from a backup. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.mariadb.models.CreateMode + :param source_server_id: Required. The source server id to restore from. + :type source_server_id: str + :param restore_point_in_time: Required. Restore point creation time (ISO8601 format), + specifying the time to restore from. + :type restore_point_in_time: ~datetime.datetime + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + 'restore_point_in_time': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + 'restore_point_in_time': {'key': 'restorePointInTime', 'type': 'iso-8601'}, + } + + def __init__( + self, + *, + source_server_id: str, + restore_point_in_time: datetime.datetime, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + super(ServerPropertiesForRestore, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'PointInTimeRestore' # type: str + self.source_server_id = source_server_id + self.restore_point_in_time = restore_point_in_time + + +class ServerSecurityAlertPolicy(ProxyResource): + """A server security alert policy. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param state: Specifies the state of the policy, whether it is enabled or disabled. Possible + values include: "Enabled", "Disabled". + :type state: str or ~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicyState + :param disabled_alerts: Specifies an array of alerts that are disabled. Allowed values are: + Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly. + :type disabled_alerts: list[str] + :param email_addresses: Specifies an array of e-mail addresses to which the alert is sent. + :type email_addresses: list[str] + :param email_account_admins: Specifies that the alert is sent to the account administrators. + :type email_account_admins: bool + :param storage_endpoint: Specifies the blob storage endpoint (e.g. + https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection + audit logs. + :type storage_endpoint: str + :param storage_account_access_key: Specifies the identifier key of the Threat Detection audit + storage account. + :type storage_account_access_key: str + :param retention_days: Specifies the number of days to keep in the Threat Detection audit logs. + :type retention_days: int + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + 'disabled_alerts': {'key': 'properties.disabledAlerts', 'type': '[str]'}, + 'email_addresses': {'key': 'properties.emailAddresses', 'type': '[str]'}, + 'email_account_admins': {'key': 'properties.emailAccountAdmins', 'type': 'bool'}, + 'storage_endpoint': {'key': 'properties.storageEndpoint', 'type': 'str'}, + 'storage_account_access_key': {'key': 'properties.storageAccountAccessKey', 'type': 'str'}, + 'retention_days': {'key': 'properties.retentionDays', 'type': 'int'}, + } + + def __init__( + self, + *, + state: Optional[Union[str, "ServerSecurityAlertPolicyState"]] = None, + disabled_alerts: Optional[List[str]] = None, + email_addresses: Optional[List[str]] = None, + email_account_admins: Optional[bool] = None, + storage_endpoint: Optional[str] = None, + storage_account_access_key: Optional[str] = None, + retention_days: Optional[int] = None, + **kwargs + ): + super(ServerSecurityAlertPolicy, self).__init__(**kwargs) + self.state = state + self.disabled_alerts = disabled_alerts + self.email_addresses = email_addresses + self.email_account_admins = email_account_admins + self.storage_endpoint = storage_endpoint + self.storage_account_access_key = storage_account_access_key + self.retention_days = retention_days + + +class ServerSecurityAlertPolicyListResult(msrest.serialization.Model): + """A list of the server's security alert policies. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicy] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerSecurityAlertPolicy]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerSecurityAlertPolicyListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ServerUpdateParameters(msrest.serialization.Model): + """Parameters allowed to update for a server. + + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.mariadb.models.Sku + :param tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :type tags: dict[str, str] + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.mariadb.models.StorageProfile + :param administrator_login_password: The password of the administrator login. + :type administrator_login_password: str + :param version: The version of a server. Possible values include: "10.2", "10.3". + :type version: str or ~azure.mgmt.rdbms.mariadb.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.mariadb.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.mariadb.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.mariadb.models.PublicNetworkAccessEnum + :param replication_role: The replication role of the server. + :type replication_role: str + """ + + _attribute_map = { + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, + 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + } + + def __init__( + self, + *, + sku: Optional["Sku"] = None, + tags: Optional[Dict[str, str]] = None, + storage_profile: Optional["StorageProfile"] = None, + administrator_login_password: Optional[str] = None, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + replication_role: Optional[str] = None, + **kwargs + ): + super(ServerUpdateParameters, self).__init__(**kwargs) + self.sku = sku + self.tags = tags + self.storage_profile = storage_profile + self.administrator_login_password = administrator_login_password + self.version = version + self.ssl_enforcement = ssl_enforcement + self.minimal_tls_version = minimal_tls_version + self.public_network_access = public_network_access + self.replication_role = replication_role + + +class Sku(msrest.serialization.Model): + """Billing information related properties of a server. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, + GP_Gen5_8. + :type name: str + :param tier: The tier of the particular SKU, e.g. Basic. Possible values include: "Basic", + "GeneralPurpose", "MemoryOptimized". + :type tier: str or ~azure.mgmt.rdbms.mariadb.models.SkuTier + :param capacity: The scale up/out capacity, representing server's compute units. + :type capacity: int + :param size: The size code, to be interpreted by resource as appropriate. + :type size: str + :param family: The family of hardware. + :type family: str + """ + + _validation = { + 'name': {'required': True}, + 'capacity': {'minimum': 0}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'tier': {'key': 'tier', 'type': 'str'}, + 'capacity': {'key': 'capacity', 'type': 'int'}, + 'size': {'key': 'size', 'type': 'str'}, + 'family': {'key': 'family', 'type': 'str'}, + } + + def __init__( + self, + *, + name: str, + tier: Optional[Union[str, "SkuTier"]] = None, + capacity: Optional[int] = None, + size: Optional[str] = None, + family: Optional[str] = None, + **kwargs + ): + super(Sku, self).__init__(**kwargs) + self.name = name + self.tier = tier + self.capacity = capacity + self.size = size + self.family = family + + +class StorageProfile(msrest.serialization.Model): + """Storage Profile properties of a server. + + :param backup_retention_days: Backup retention days for the server. + :type backup_retention_days: int + :param geo_redundant_backup: Enable Geo-redundant or not for server backup. Possible values + include: "Enabled", "Disabled". + :type geo_redundant_backup: str or ~azure.mgmt.rdbms.mariadb.models.GeoRedundantBackup + :param storage_mb: Max storage allowed for a server. + :type storage_mb: int + :param storage_autogrow: Enable Storage Auto Grow. Possible values include: "Enabled", + "Disabled". + :type storage_autogrow: str or ~azure.mgmt.rdbms.mariadb.models.StorageAutogrow + """ + + _attribute_map = { + 'backup_retention_days': {'key': 'backupRetentionDays', 'type': 'int'}, + 'geo_redundant_backup': {'key': 'geoRedundantBackup', 'type': 'str'}, + 'storage_mb': {'key': 'storageMB', 'type': 'int'}, + 'storage_autogrow': {'key': 'storageAutogrow', 'type': 'str'}, + } + + def __init__( + self, + *, + backup_retention_days: Optional[int] = None, + geo_redundant_backup: Optional[Union[str, "GeoRedundantBackup"]] = None, + storage_mb: Optional[int] = None, + storage_autogrow: Optional[Union[str, "StorageAutogrow"]] = None, + **kwargs + ): + super(StorageProfile, self).__init__(**kwargs) + self.backup_retention_days = backup_retention_days + self.geo_redundant_backup = geo_redundant_backup + self.storage_mb = storage_mb + self.storage_autogrow = storage_autogrow + + +class TagsObject(msrest.serialization.Model): + """Tags object for patch operations. + + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + """ + + _attribute_map = { + 'tags': {'key': 'tags', 'type': '{str}'}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + **kwargs + ): + super(TagsObject, self).__init__(**kwargs) + self.tags = tags + + +class TopQueryStatisticsInput(msrest.serialization.Model): + """Input to get top query statistics. + + All required parameters must be populated in order to send to Azure. + + :param number_of_top_queries: Required. Max number of top queries to return. + :type number_of_top_queries: int + :param aggregation_function: Required. Aggregation function name. + :type aggregation_function: str + :param observed_metric: Required. Observed metric name. + :type observed_metric: str + :param observation_start_time: Required. Observation start time. + :type observation_start_time: ~datetime.datetime + :param observation_end_time: Required. Observation end time. + :type observation_end_time: ~datetime.datetime + :param aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :type aggregation_window: str + """ + + _validation = { + 'number_of_top_queries': {'required': True}, + 'aggregation_function': {'required': True}, + 'observed_metric': {'required': True}, + 'observation_start_time': {'required': True}, + 'observation_end_time': {'required': True}, + 'aggregation_window': {'required': True}, + } + + _attribute_map = { + 'number_of_top_queries': {'key': 'properties.numberOfTopQueries', 'type': 'int'}, + 'aggregation_function': {'key': 'properties.aggregationFunction', 'type': 'str'}, + 'observed_metric': {'key': 'properties.observedMetric', 'type': 'str'}, + 'observation_start_time': {'key': 'properties.observationStartTime', 'type': 'iso-8601'}, + 'observation_end_time': {'key': 'properties.observationEndTime', 'type': 'iso-8601'}, + 'aggregation_window': {'key': 'properties.aggregationWindow', 'type': 'str'}, + } + + def __init__( + self, + *, + number_of_top_queries: int, + aggregation_function: str, + observed_metric: str, + observation_start_time: datetime.datetime, + observation_end_time: datetime.datetime, + aggregation_window: str, + **kwargs + ): + super(TopQueryStatisticsInput, self).__init__(**kwargs) + self.number_of_top_queries = number_of_top_queries + self.aggregation_function = aggregation_function + self.observed_metric = observed_metric + self.observation_start_time = observation_start_time + self.observation_end_time = observation_end_time + self.aggregation_window = aggregation_window + + +class TopQueryStatisticsResultList(msrest.serialization.Model): + """A list of query statistics. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of top query statistics. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.QueryStatistic] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[QueryStatistic]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(TopQueryStatisticsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class VirtualNetworkRule(ProxyResource): + """A virtual network rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param virtual_network_subnet_id: The ARM resource id of the virtual network subnet. + :type virtual_network_subnet_id: str + :param ignore_missing_vnet_service_endpoint: Create firewall rule before the virtual network + has vnet service endpoint enabled. + :type ignore_missing_vnet_service_endpoint: bool + :ivar state: Virtual Network Rule State. Possible values include: "Initializing", "InProgress", + "Ready", "Deleting", "Unknown". + :vartype state: str or ~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRuleState + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'state': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'virtual_network_subnet_id': {'key': 'properties.virtualNetworkSubnetId', 'type': 'str'}, + 'ignore_missing_vnet_service_endpoint': {'key': 'properties.ignoreMissingVnetServiceEndpoint', 'type': 'bool'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + } + + def __init__( + self, + *, + virtual_network_subnet_id: Optional[str] = None, + ignore_missing_vnet_service_endpoint: Optional[bool] = None, + **kwargs + ): + super(VirtualNetworkRule, self).__init__(**kwargs) + self.virtual_network_subnet_id = virtual_network_subnet_id + self.ignore_missing_vnet_service_endpoint = ignore_missing_vnet_service_endpoint + self.state = None + + +class VirtualNetworkRuleListResult(msrest.serialization.Model): + """A list of virtual network rules. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRule] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[VirtualNetworkRule]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(VirtualNetworkRuleListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class WaitStatistic(ProxyResource): + """Represents a Wait Statistic. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param start_time: Observation start time. + :type start_time: ~datetime.datetime + :param end_time: Observation end time. + :type end_time: ~datetime.datetime + :param event_name: Wait event name. + :type event_name: str + :param event_type_name: Wait event type name. + :type event_type_name: str + :param query_id: Database query identifier. + :type query_id: long + :param database_name: Database Name. + :type database_name: str + :param user_id: Database user identifier. + :type user_id: long + :param count: Wait event count observed in this time interval. + :type count: long + :param total_time_in_ms: Total time of wait in milliseconds in this time interval. + :type total_time_in_ms: float + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, + 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, + 'event_name': {'key': 'properties.eventName', 'type': 'str'}, + 'event_type_name': {'key': 'properties.eventTypeName', 'type': 'str'}, + 'query_id': {'key': 'properties.queryId', 'type': 'long'}, + 'database_name': {'key': 'properties.databaseName', 'type': 'str'}, + 'user_id': {'key': 'properties.userId', 'type': 'long'}, + 'count': {'key': 'properties.count', 'type': 'long'}, + 'total_time_in_ms': {'key': 'properties.totalTimeInMs', 'type': 'float'}, + } + + def __init__( + self, + *, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + event_name: Optional[str] = None, + event_type_name: Optional[str] = None, + query_id: Optional[int] = None, + database_name: Optional[str] = None, + user_id: Optional[int] = None, + count: Optional[int] = None, + total_time_in_ms: Optional[float] = None, + **kwargs + ): + super(WaitStatistic, self).__init__(**kwargs) + self.start_time = start_time + self.end_time = end_time + self.event_name = event_name + self.event_type_name = event_type_name + self.query_id = query_id + self.database_name = database_name + self.user_id = user_id + self.count = count + self.total_time_in_ms = total_time_in_ms + + +class WaitStatisticsInput(msrest.serialization.Model): + """Input to get wait statistics. + + All required parameters must be populated in order to send to Azure. + + :param observation_start_time: Required. Observation start time. + :type observation_start_time: ~datetime.datetime + :param observation_end_time: Required. Observation end time. + :type observation_end_time: ~datetime.datetime + :param aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :type aggregation_window: str + """ + + _validation = { + 'observation_start_time': {'required': True}, + 'observation_end_time': {'required': True}, + 'aggregation_window': {'required': True}, + } + + _attribute_map = { + 'observation_start_time': {'key': 'properties.observationStartTime', 'type': 'iso-8601'}, + 'observation_end_time': {'key': 'properties.observationEndTime', 'type': 'iso-8601'}, + 'aggregation_window': {'key': 'properties.aggregationWindow', 'type': 'str'}, + } + + def __init__( + self, + *, + observation_start_time: datetime.datetime, + observation_end_time: datetime.datetime, + aggregation_window: str, + **kwargs + ): + super(WaitStatisticsInput, self).__init__(**kwargs) + self.observation_start_time = observation_start_time + self.observation_end_time = observation_end_time + self.aggregation_window = aggregation_window + + +class WaitStatisticsResultList(msrest.serialization.Model): + """A list of wait statistics. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of wait statistics. + :vartype value: list[~azure.mgmt.rdbms.mariadb.models.WaitStatistic] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[WaitStatistic]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(WaitStatisticsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..33ffedbabf7ff86392a81902b2c11c02533cb88c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/__init__.py @@ -0,0 +1,59 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._servers_operations import ServersOperations +from ._replicas_operations import ReplicasOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._virtual_network_rules_operations import VirtualNetworkRulesOperations +from ._databases_operations import DatabasesOperations +from ._configurations_operations import ConfigurationsOperations +from ._server_parameters_operations import ServerParametersOperations +from ._log_files_operations import LogFilesOperations +from ._recoverable_servers_operations import RecoverableServersOperations +from ._server_based_performance_tier_operations import ServerBasedPerformanceTierOperations +from ._location_based_performance_tier_operations import LocationBasedPerformanceTierOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._operations import Operations +from ._query_texts_operations import QueryTextsOperations +from ._top_query_statistics_operations import TopQueryStatisticsOperations +from ._wait_statistics_operations import WaitStatisticsOperations +from ._maria_db_management_client_operations import MariaDBManagementClientOperationsMixin +from ._advisors_operations import AdvisorsOperations +from ._recommended_actions_operations import RecommendedActionsOperations +from ._location_based_recommended_action_sessions_operation_status_operations import LocationBasedRecommendedActionSessionsOperationStatusOperations +from ._location_based_recommended_action_sessions_result_operations import LocationBasedRecommendedActionSessionsResultOperations +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._private_link_resources_operations import PrivateLinkResourcesOperations +from ._server_security_alert_policies_operations import ServerSecurityAlertPoliciesOperations + +__all__ = [ + 'ServersOperations', + 'ReplicasOperations', + 'FirewallRulesOperations', + 'VirtualNetworkRulesOperations', + 'DatabasesOperations', + 'ConfigurationsOperations', + 'ServerParametersOperations', + 'LogFilesOperations', + 'RecoverableServersOperations', + 'ServerBasedPerformanceTierOperations', + 'LocationBasedPerformanceTierOperations', + 'CheckNameAvailabilityOperations', + 'Operations', + 'QueryTextsOperations', + 'TopQueryStatisticsOperations', + 'WaitStatisticsOperations', + 'MariaDBManagementClientOperationsMixin', + 'AdvisorsOperations', + 'RecommendedActionsOperations', + 'LocationBasedRecommendedActionSessionsOperationStatusOperations', + 'LocationBasedRecommendedActionSessionsResultOperations', + 'PrivateEndpointConnectionsOperations', + 'PrivateLinkResourcesOperations', + 'ServerSecurityAlertPoliciesOperations', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_advisors_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_advisors_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..708e89d315b04bcfd97f90d900aaf7fb8ccfd579 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_advisors_operations.py @@ -0,0 +1,184 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class AdvisorsOperations(object): + """AdvisorsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + advisor_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.Advisor" + """Get a recommendation action advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Advisor, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.Advisor + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Advisor"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'advisorName': self._serialize.url("advisor_name", advisor_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Advisor', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors/{advisorName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.AdvisorsResultList"] + """List recommendation action advisors. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AdvisorsResultList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.AdvisorsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.AdvisorsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('AdvisorsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_check_name_availability_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_check_name_availability_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d94451aa23324a084060a33434de17ca35db8525 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_check_name_availability_operations.py @@ -0,0 +1,105 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class CheckNameAvailabilityOperations(object): + """CheckNameAvailabilityOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def execute( + self, + name_availability_request, # type: "_models.NameAvailabilityRequest" + **kwargs # type: Any + ): + # type: (...) -> "_models.NameAvailability" + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. + :type name_availability_request: ~azure.mgmt.rdbms.mariadb.models.NameAvailabilityRequest + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.NameAvailability + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.execute.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('NameAvailability', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBForMariaDB/checkNameAvailability'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_configurations_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_configurations_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..3cc43d78c8f40770e3315ff75291c18a8ca61574 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_configurations_operations.py @@ -0,0 +1,321 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ConfigurationsOperations(object): + """ConfigurationsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + configuration_name, # type: str + parameters, # type: "_models.Configuration" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Configuration"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Configuration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + configuration_name, # type: str + parameters, # type: "_models.Configuration" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Configuration"] + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Configuration or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mariadb.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.Configuration" + """Gets information about a configuration of server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Configuration, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.Configuration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ConfigurationListResult"] + """List all the configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConfigurationListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/configurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_databases_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_databases_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8a3ab66a019cbb81fe9d020428ca80df1a4442 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_databases_operations.py @@ -0,0 +1,441 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class DatabasesOperations(object): + """DatabasesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + parameters, # type: "_models.Database" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Database"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Database"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Database') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Database', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + parameters, # type: "_models.Database" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Database"] + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.Database + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Database or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mariadb.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.Database" + """Gets information about a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Database, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.Database + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.DatabaseListResult"] + """List all the databases in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DatabaseListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.DatabaseListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.DatabaseListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('DatabaseListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/databases'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_firewall_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_firewall_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..f621d66b4bdfe21f62fbbf777687710b2b431591 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_firewall_rules_operations.py @@ -0,0 +1,441 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class FirewallRulesOperations(object): + """FirewallRulesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + parameters, # type: "_models.FirewallRule" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.FirewallRule"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FirewallRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'FirewallRule') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + parameters, # type: "_models.FirewallRule" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.FirewallRule"] + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.FirewallRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either FirewallRule or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mariadb.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.FirewallRule" + """Gets information about a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FirewallRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.FirewallRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.FirewallRuleListResult"] + """List all the firewall rules in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FirewallRuleListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.FirewallRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('FirewallRuleListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/firewallRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_location_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_location_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d721ed5a36b9cc2a632b99694fab92cd3773f5dd --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_location_based_performance_tier_operations.py @@ -0,0 +1,117 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedPerformanceTierOperations(object): + """LocationBasedPerformanceTierOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + location_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.PerformanceTierListResult"] + """List all the performance tiers at specified location in a given subscription. + + :param location_name: The name of the location. + :type location_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('PerformanceTierListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBForMariaDB/locations/{locationName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_location_based_recommended_action_sessions_operation_status_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_location_based_recommended_action_sessions_operation_status_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..e62d7533cd56e3f04be4a79d9caeff0b24f9d64f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_location_based_recommended_action_sessions_operation_status_operations.py @@ -0,0 +1,104 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedRecommendedActionSessionsOperationStatusOperations(object): + """LocationBasedRecommendedActionSessionsOperationStatusOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + location_name, # type: str + operation_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.RecommendedActionSessionsOperationStatus" + """Recommendation action session operation status. + + :param location_name: The name of the location. + :type location_name: str + :param operation_id: The operation identifier. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecommendedActionSessionsOperationStatus, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.RecommendedActionSessionsOperationStatus + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendedActionSessionsOperationStatus"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + 'operationId': self._serialize.url("operation_id", operation_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecommendedActionSessionsOperationStatus', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMariaDB/locations/{locationName}/recommendedActionSessionsAzureAsyncOperation/{operationId}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_location_based_recommended_action_sessions_result_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_location_based_recommended_action_sessions_result_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..343ae273be33ec6d09e53c683bd1b06a8b2f8d0b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_location_based_recommended_action_sessions_result_operations.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedRecommendedActionSessionsResultOperations(object): + """LocationBasedRecommendedActionSessionsResultOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + location_name, # type: str + operation_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.RecommendationActionsResultList"] + """Recommendation action session operation result. + + :param location_name: The name of the location. + :type location_name: str + :param operation_id: The operation identifier. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RecommendationActionsResultList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.RecommendationActionsResultListor ~azure.mgmt.rdbms.mariadb.models.RecommendationActionsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationActionsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + 'operationId': self._serialize.url("operation_id", operation_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('RecommendationActionsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMariaDB/locations/{locationName}/recommendedActionSessionsOperationResults/{operationId}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_log_files_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_log_files_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..1d608a74e608a40c746d989b019a4bf983df0426 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_log_files_operations.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class LogFilesOperations(object): + """LogFilesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.LogFileListResult"] + """List all the log files in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either LogFileListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.LogFileListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.LogFileListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('LogFileListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/logFiles'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_maria_db_management_client_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_maria_db_management_client_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b028f5b7d1aea739357f0f7083800aa2f7ca8453 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_maria_db_management_client_operations.py @@ -0,0 +1,207 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class MariaDBManagementClientOperationsMixin(object): + + def reset_query_performance_insight_data( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.QueryPerformanceInsightResetDataResult" + """Reset data for Query Performance Insight. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryPerformanceInsightResetDataResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.QueryPerformanceInsightResetDataResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryPerformanceInsightResetDataResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.reset_query_performance_insight_data.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryPerformanceInsightResetDataResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + reset_query_performance_insight_data.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/resetQueryPerformanceInsightData'} # type: ignore + + def _create_recommended_action_session_initial( + self, + resource_group_name, # type: str + server_name, # type: str + advisor_name, # type: str + database_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + + # Construct URL + url = self._create_recommended_action_session_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'advisorName': self._serialize.url("advisor_name", advisor_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + query_parameters['databaseName'] = self._serialize.query("database_name", database_name, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _create_recommended_action_session_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession'} # type: ignore + + def begin_create_recommended_action_session( + self, + resource_group_name, # type: str + server_name, # type: str + advisor_name, # type: str + database_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Create recommendation action session for the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_recommended_action_session_initial( + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'advisorName': self._serialize.url("advisor_name", advisor_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_recommended_action_session.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..07746642fa6b3c4aebee2eb591454f405b9b3cb7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_operations.py @@ -0,0 +1,92 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class Operations(object): + """Operations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> "_models.OperationListResult" + """Lists all of the available REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationListResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.OperationListResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.list.metadata['url'] # type: ignore + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + list.metadata = {'url': '/providers/Microsoft.DBForMariaDB/operations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_private_endpoint_connections_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_private_endpoint_connections_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..a9985f5e8097e13ef7a5578ee99c9245b436b671 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_private_endpoint_connections_operations.py @@ -0,0 +1,574 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class PrivateEndpointConnectionsOperations(object): + """PrivateEndpointConnectionsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.PrivateEndpointConnection" + """Gets a private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnection + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + parameters, # type: "_models.PrivateEndpointConnection" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.PrivateEndpointConnection"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.PrivateEndpointConnection"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'PrivateEndpointConnection') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + parameters, # type: "_models.PrivateEndpointConnection" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.PrivateEndpointConnection"] + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: + :type parameters: ~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnection + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def _update_tags_initial( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + parameters, # type: "_models.TagsObject" + **kwargs # type: Any + ): + # type: (...) -> "_models.PrivateEndpointConnection" + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_tags_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'TagsObject') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_tags_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def begin_update_tags( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + parameters, # type: "_models.TagsObject" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.PrivateEndpointConnection"] + """Updates tags on private endpoint connection. + + Updates private endpoint connection with the specified tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: Parameters supplied to the Update private endpoint connection Tags + operation. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.TagsObject + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._update_tags_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.PrivateEndpointConnectionListResult"] + """Gets all private endpoint connections on a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateEndpointConnectionListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.PrivateEndpointConnectionListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnectionListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateEndpointConnections'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_private_link_resources_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_private_link_resources_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..56891f30503ef8d374024e2fe05310ec541f4b2b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_private_link_resources_operations.py @@ -0,0 +1,184 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class PrivateLinkResourcesOperations(object): + """PrivateLinkResourcesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.PrivateLinkResourceListResult"] + """Gets the private link resources for MariaDB server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateLinkResourceListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.PrivateLinkResourceListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('PrivateLinkResourceListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateLinkResources'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + group_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.PrivateLinkResource" + """Gets a private link resource for MariaDB server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param group_name: The name of the private link resource. + :type group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateLinkResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.PrivateLinkResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'groupName': self._serialize.url("group_name", group_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateLinkResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/privateLinkResources/{groupName}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_query_texts_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_query_texts_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..7d363e73cae3bfb767cd931dccd1468c133ef285 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_query_texts_operations.py @@ -0,0 +1,188 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, List, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class QueryTextsOperations(object): + """QueryTextsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + query_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.QueryText" + """Retrieve the Query-Store query texts for the queryId. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_id: The Query-Store query identifier. + :type query_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryText, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.QueryText + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryText"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'queryId': self._serialize.url("query_id", query_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryText', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/queryTexts/{queryId}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + query_ids, # type: List[str] + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.QueryTextsResultList"] + """Retrieve the Query-Store query texts for specified queryIds. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_ids: The query identifiers. + :type query_ids: list[str] + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either QueryTextsResultList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.QueryTextsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryTextsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + query_parameters['queryIds'] = [self._serialize.query("query_ids", q, 'str') if q is not None else '' for q in query_ids] + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('QueryTextsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/queryTexts'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_recommended_actions_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_recommended_actions_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..be8c818d10425fe44d9f4b5cb28f5c285be4cdd5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_recommended_actions_operations.py @@ -0,0 +1,197 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class RecommendedActionsOperations(object): + """RecommendedActionsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + advisor_name, # type: str + recommended_action_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.RecommendationAction" + """Retrieve recommended actions from the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param recommended_action_name: The recommended action name. + :type recommended_action_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecommendationAction, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.RecommendationAction + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationAction"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'advisorName': self._serialize.url("advisor_name", advisor_name, 'str'), + 'recommendedActionName': self._serialize.url("recommended_action_name", recommended_action_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecommendationAction', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + advisor_name, # type: str + session_id=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.RecommendationActionsResultList"] + """Retrieve recommended actions from the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param session_id: The recommendation action session identifier. + :type session_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RecommendationActionsResultList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.RecommendationActionsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationActionsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'advisorName': self._serialize.url("advisor_name", advisor_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + if session_id is not None: + query_parameters['sessionId'] = self._serialize.query("session_id", session_id, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('RecommendationActionsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/advisors/{advisorName}/recommendedActions'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_recoverable_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_recoverable_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..c7dc536fcd76c9fa1226b593dc46b1f74364e44a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_recoverable_servers_operations.py @@ -0,0 +1,104 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class RecoverableServersOperations(object): + """RecoverableServersOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.RecoverableServerResource" + """Gets a recoverable MariaDB Server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecoverableServerResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.RecoverableServerResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecoverableServerResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecoverableServerResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/recoverableServers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_replicas_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_replicas_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..835a4ba48fa0ea829fe8fc8be7c0cf9d52649089 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_replicas_operations.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ReplicasOperations(object): + """ReplicasOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerListResult"] + """List all the replicas for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/replicas'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_server_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_server_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d0adae4a1938f6463f16fa23c81e712d98c6b2b7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_server_based_performance_tier_operations.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ServerBasedPerformanceTierOperations(object): + """ServerBasedPerformanceTierOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.PerformanceTierListResult"] + """List all the performance tiers for a MariaDB server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('PerformanceTierListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_server_parameters_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_server_parameters_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..5929b5d5996aa7cf02c7e0248b75e86a3c4cf164 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_server_parameters_operations.py @@ -0,0 +1,175 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ServerParametersOperations(object): + """ServerParametersOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _list_update_configurations_initial( + self, + resource_group_name, # type: str + server_name, # type: str + value, # type: "_models.ConfigurationListResult" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.ConfigurationListResult"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ConfigurationListResult"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._list_update_configurations_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(value, 'ConfigurationListResult') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _list_update_configurations_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/updateConfigurations'} # type: ignore + + def begin_list_update_configurations( + self, + resource_group_name, # type: str + server_name, # type: str + value, # type: "_models.ConfigurationListResult" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.ConfigurationListResult"] + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param value: The parameters for updating a list of server configuration. + :type value: ~azure.mgmt.rdbms.mariadb.models.ConfigurationListResult + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either ConfigurationListResult or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mariadb.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._list_update_configurations_initial( + resource_group_name=resource_group_name, + server_name=server_name, + value=value, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_list_update_configurations.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/updateConfigurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_server_security_alert_policies_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_server_security_alert_policies_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..47c0e2fd41762d971de65704e93961313cfed0ff --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_server_security_alert_policies_operations.py @@ -0,0 +1,321 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ServerSecurityAlertPoliciesOperations(object): + """ServerSecurityAlertPoliciesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + security_alert_policy_name, # type: Union[str, "_models.SecurityAlertPolicyName"] + **kwargs # type: Any + ): + # type: (...) -> "_models.ServerSecurityAlertPolicy" + """Get a server's security alert policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the security alert policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mariadb.models.SecurityAlertPolicyName + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerSecurityAlertPolicy, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicy + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + security_alert_policy_name, # type: Union[str, "_models.SecurityAlertPolicyName"] + parameters, # type: "_models.ServerSecurityAlertPolicy" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.ServerSecurityAlertPolicy"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ServerSecurityAlertPolicy"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerSecurityAlertPolicy') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + security_alert_policy_name, # type: Union[str, "_models.SecurityAlertPolicyName"] + parameters, # type: "_models.ServerSecurityAlertPolicy" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.ServerSecurityAlertPolicy"] + """Creates or updates a threat detection policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the threat detection policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mariadb.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicy + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either ServerSecurityAlertPolicy or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + security_alert_policy_name=security_alert_policy_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerSecurityAlertPolicyListResult"] + """Get the server's threat detection policies. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerSecurityAlertPolicyListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.ServerSecurityAlertPolicyListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicyListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerSecurityAlertPolicyListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/securityAlertPolicies'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..966a5d6a3e620acf6de9dee808b8095d635a4781 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_servers_operations.py @@ -0,0 +1,948 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ServersOperations(object): + """ServersOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_initial( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.ServerForCreate" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Server"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerForCreate') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + def begin_create( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.ServerForCreate" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Server"] + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.ServerForCreate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mariadb.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + def _update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.ServerUpdateParameters" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Server"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerUpdateParameters') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + def begin_update( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.ServerUpdateParameters" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Server"] + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.ServerUpdateParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mariadb.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.Server" + """Gets information about a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Server, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.Server + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}'} # type: ignore + + def list_by_resource_group( + self, + resource_group_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerListResult"] + """List all the servers in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_resource_group.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers'} # type: ignore + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerListResult"] + """List all the servers in a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBForMariaDB/servers'} # type: ignore + + def _restart_initial( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._restart_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/restart'} # type: ignore + + def begin_restart( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._restart_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/restart'} # type: ignore + + def _start_initial( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + accept = "application/json" + + # Construct URL + url = self._start_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CloudErrorAutoGenerated, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/start'} # type: ignore + + def begin_start( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Starts a stopped server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._start_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/start'} # type: ignore + + def _stop_initial( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + accept = "application/json" + + # Construct URL + url = self._stop_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CloudErrorAutoGenerated, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _stop_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/stop'} # type: ignore + + def begin_stop( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Stops a running server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._stop_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/stop'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_top_query_statistics_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_top_query_statistics_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..fc86c83c2e9f146a99edbf60decd051cd327f97c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_top_query_statistics_operations.py @@ -0,0 +1,195 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class TopQueryStatisticsOperations(object): + """TopQueryStatisticsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + query_statistic_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.QueryStatistic" + """Retrieve the query statistic for specified identifier. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_statistic_id: The Query Statistic identifier. + :type query_statistic_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryStatistic, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.QueryStatistic + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryStatistic"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'queryStatisticId': self._serialize.url("query_statistic_id", query_statistic_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryStatistic', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/topQueryStatistics/{queryStatisticId}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.TopQueryStatisticsInput" + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.TopQueryStatisticsResultList"] + """Retrieve the Query-Store top queries for specified metric and aggregation. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for retrieving top query statistics. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.TopQueryStatisticsInput + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either TopQueryStatisticsResultList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.TopQueryStatisticsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.TopQueryStatisticsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = "application/json" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'TopQueryStatisticsInput') + body_content_kwargs['content'] = body_content + request = self._client.get(url, query_parameters, header_parameters, **body_content_kwargs) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'TopQueryStatisticsInput') + body_content_kwargs['content'] = body_content + request = self._client.get(url, query_parameters, header_parameters, **body_content_kwargs) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('TopQueryStatisticsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/topQueryStatistics'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_virtual_network_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_virtual_network_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..78eac2a7cb56014104b8e4cf7662500772dd67ee --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_virtual_network_rules_operations.py @@ -0,0 +1,439 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class VirtualNetworkRulesOperations(object): + """VirtualNetworkRulesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + virtual_network_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.VirtualNetworkRule" + """Gets a virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + virtual_network_rule_name, # type: str + parameters, # type: "_models.VirtualNetworkRule" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.VirtualNetworkRule"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.VirtualNetworkRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'VirtualNetworkRule') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + virtual_network_rule_name, # type: str + parameters, # type: "_models.VirtualNetworkRule" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.VirtualNetworkRule"] + """Creates or updates an existing virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :param parameters: The requested virtual Network Rule Resource state. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either VirtualNetworkRule or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + virtual_network_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + virtual_network_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes the virtual network rule with the given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.VirtualNetworkRuleListResult"] + """Gets a list of virtual network rules in a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either VirtualNetworkRuleListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.VirtualNetworkRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('VirtualNetworkRuleListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMariaDB/servers/{serverName}/virtualNetworkRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_wait_statistics_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_wait_statistics_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b831b22b214ee88225ddcddeb27b35d8547d7f22 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mariadb/operations/_wait_statistics_operations.py @@ -0,0 +1,195 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class WaitStatisticsOperations(object): + """WaitStatisticsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mariadb.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + wait_statistics_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.WaitStatistic" + """Retrieve wait statistics for specified identifier. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param wait_statistics_id: The Wait Statistic identifier. + :type wait_statistics_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: WaitStatistic, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mariadb.models.WaitStatistic + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.WaitStatistic"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'waitStatisticsId': self._serialize.url("wait_statistics_id", wait_statistics_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('WaitStatistic', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/waitStatistics/{waitStatisticsId}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.WaitStatisticsInput" + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.WaitStatisticsResultList"] + """Retrieve wait statistics for specified aggregation window. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for retrieving wait statistics. + :type parameters: ~azure.mgmt.rdbms.mariadb.models.WaitStatisticsInput + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either WaitStatisticsResultList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mariadb.models.WaitStatisticsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.WaitStatisticsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = "application/json" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'WaitStatisticsInput') + body_content_kwargs['content'] = body_content + request = self._client.get(url, query_parameters, header_parameters, **body_content_kwargs) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'WaitStatisticsInput') + body_content_kwargs['content'] = body_content + request = self._client.get(url, query_parameters, header_parameters, **body_content_kwargs) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('WaitStatisticsResultList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMariaDB/servers/{serverName}/waitStatistics'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..089186ed748e706ccbbdf60a2d391445b77a6a0d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/__init__.py @@ -0,0 +1,18 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._my_sql_management_client import MySQLManagementClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['MySQLManagementClient'] + +# `._patch.py` is used for handwritten extensions to the generated code +# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +from ._patch import patch_sdk +patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..e4728c56ed529959a356891a2ad5dd6e540ccf04 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class MySQLManagementClientConfiguration(Configuration): + """Configuration for MySQLManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + super(MySQLManagementClientConfiguration, self).__init__(**kwargs) + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_my_sql_management_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_my_sql_management_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a2474de2c67239702e435a61b9752094392c617d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_my_sql_management_client.py @@ -0,0 +1,176 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient +from msrest import Deserializer, Serializer + +from . import models +from ._configuration import MySQLManagementClientConfiguration +from .operations import AdvisorsOperations, CheckNameAvailabilityOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, LocationBasedPerformanceTierOperations, LocationBasedRecommendedActionSessionsOperationStatusOperations, LocationBasedRecommendedActionSessionsResultOperations, LogFilesOperations, MySQLManagementClientOperationsMixin, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, QueryTextsOperations, RecommendedActionsOperations, RecoverableServersOperations, ReplicasOperations, ServerAdministratorsOperations, ServerBasedPerformanceTierOperations, ServerKeysOperations, ServerParametersOperations, ServerSecurityAlertPoliciesOperations, ServersOperations, TopQueryStatisticsOperations, VirtualNetworkRulesOperations, WaitStatisticsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + +class MySQLManagementClient(MySQLManagementClientOperationsMixin): + """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure MySQL resources including servers, databases, firewall rules, VNET rules, log files and configurations with new business model. + + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.mysql.operations.ServersOperations + :ivar replicas: ReplicasOperations operations + :vartype replicas: azure.mgmt.rdbms.mysql.operations.ReplicasOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.rdbms.mysql.operations.FirewallRulesOperations + :ivar virtual_network_rules: VirtualNetworkRulesOperations operations + :vartype virtual_network_rules: azure.mgmt.rdbms.mysql.operations.VirtualNetworkRulesOperations + :ivar databases: DatabasesOperations operations + :vartype databases: azure.mgmt.rdbms.mysql.operations.DatabasesOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: azure.mgmt.rdbms.mysql.operations.ConfigurationsOperations + :ivar server_parameters: ServerParametersOperations operations + :vartype server_parameters: azure.mgmt.rdbms.mysql.operations.ServerParametersOperations + :ivar log_files: LogFilesOperations operations + :vartype log_files: azure.mgmt.rdbms.mysql.operations.LogFilesOperations + :ivar server_administrators: ServerAdministratorsOperations operations + :vartype server_administrators: + azure.mgmt.rdbms.mysql.operations.ServerAdministratorsOperations + :ivar recoverable_servers: RecoverableServersOperations operations + :vartype recoverable_servers: azure.mgmt.rdbms.mysql.operations.RecoverableServersOperations + :ivar server_based_performance_tier: ServerBasedPerformanceTierOperations operations + :vartype server_based_performance_tier: + azure.mgmt.rdbms.mysql.operations.ServerBasedPerformanceTierOperations + :ivar location_based_performance_tier: LocationBasedPerformanceTierOperations operations + :vartype location_based_performance_tier: + azure.mgmt.rdbms.mysql.operations.LocationBasedPerformanceTierOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: + azure.mgmt.rdbms.mysql.operations.CheckNameAvailabilityOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.mysql.operations.Operations + :ivar server_security_alert_policies: ServerSecurityAlertPoliciesOperations operations + :vartype server_security_alert_policies: + azure.mgmt.rdbms.mysql.operations.ServerSecurityAlertPoliciesOperations + :ivar query_texts: QueryTextsOperations operations + :vartype query_texts: azure.mgmt.rdbms.mysql.operations.QueryTextsOperations + :ivar top_query_statistics: TopQueryStatisticsOperations operations + :vartype top_query_statistics: azure.mgmt.rdbms.mysql.operations.TopQueryStatisticsOperations + :ivar wait_statistics: WaitStatisticsOperations operations + :vartype wait_statistics: azure.mgmt.rdbms.mysql.operations.WaitStatisticsOperations + :ivar advisors: AdvisorsOperations operations + :vartype advisors: azure.mgmt.rdbms.mysql.operations.AdvisorsOperations + :ivar recommended_actions: RecommendedActionsOperations operations + :vartype recommended_actions: azure.mgmt.rdbms.mysql.operations.RecommendedActionsOperations + :ivar location_based_recommended_action_sessions_operation_status: + LocationBasedRecommendedActionSessionsOperationStatusOperations operations + :vartype location_based_recommended_action_sessions_operation_status: + azure.mgmt.rdbms.mysql.operations.LocationBasedRecommendedActionSessionsOperationStatusOperations + :ivar location_based_recommended_action_sessions_result: + LocationBasedRecommendedActionSessionsResultOperations operations + :vartype location_based_recommended_action_sessions_result: + azure.mgmt.rdbms.mysql.operations.LocationBasedRecommendedActionSessionsResultOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: + azure.mgmt.rdbms.mysql.operations.PrivateEndpointConnectionsOperations + :ivar private_link_resources: PrivateLinkResourcesOperations operations + :vartype private_link_resources: + azure.mgmt.rdbms.mysql.operations.PrivateLinkResourcesOperations + :ivar server_keys: ServerKeysOperations operations + :vartype server_keys: azure.mgmt.rdbms.mysql.operations.ServerKeysOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param base_url: Service URL. Default value is 'https://management.azure.com'. + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = MySQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.servers = ServersOperations(self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations(self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.virtual_network_rules = VirtualNetworkRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations(self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.server_parameters = ServerParametersOperations(self._client, self._config, self._serialize, self._deserialize) + self.log_files = LogFilesOperations(self._client, self._config, self._serialize, self._deserialize) + self.server_administrators = ServerAdministratorsOperations(self._client, self._config, self._serialize, self._deserialize) + self.recoverable_servers = RecoverableServersOperations(self._client, self._config, self._serialize, self._deserialize) + self.server_based_performance_tier = ServerBasedPerformanceTierOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_performance_tier = LocationBasedPerformanceTierOperations(self._client, self._config, self._serialize, self._deserialize) + self.check_name_availability = CheckNameAvailabilityOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.server_security_alert_policies = ServerSecurityAlertPoliciesOperations(self._client, self._config, self._serialize, self._deserialize) + self.query_texts = QueryTextsOperations(self._client, self._config, self._serialize, self._deserialize) + self.top_query_statistics = TopQueryStatisticsOperations(self._client, self._config, self._serialize, self._deserialize) + self.wait_statistics = WaitStatisticsOperations(self._client, self._config, self._serialize, self._deserialize) + self.advisors = AdvisorsOperations(self._client, self._config, self._serialize, self._deserialize) + self.recommended_actions = RecommendedActionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_recommended_action_sessions_operation_status = LocationBasedRecommendedActionSessionsOperationStatusOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_recommended_action_sessions_result = LocationBasedRecommendedActionSessionsResultOperations(self._client, self._config, self._serialize, self._deserialize) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) + self.server_keys = ServerKeysOperations(self._client, self._config, self._serialize, self._deserialize) + + + def _send_request( + self, + request, # type: HttpRequest + **kwargs: Any + ) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> MySQLManagementClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..74e48ecd07cf36d7740246e19b7fd4a701a5130b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_patch.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# This file is used for handwritten extensions to the generated code. Example: +# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +def patch_sdk(): + pass \ No newline at end of file diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..138f663c53a4e573c9426047e878528c95c6326f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [ + c for c in formatted_components if "{}".format(key.args[0]) not in c + ] + template = "/".join(components) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..c1257f7f4e111146dae88528000dc4841f2ef2aa --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "10.1.0" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..910a198089c91c8b7847113ac5fae1887eb9b197 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/__init__.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._my_sql_management_client import MySQLManagementClient +__all__ = ['MySQLManagementClient'] + +# `._patch.py` is used for handwritten extensions to the generated code +# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +from ._patch import patch_sdk +patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..e2bab7f4cf3f24188e2c95d55734484bc072e23d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/_configuration.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class MySQLManagementClientConfiguration(Configuration): + """Configuration for MySQLManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + super(MySQLManagementClientConfiguration, self).__init__(**kwargs) + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/_my_sql_management_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/_my_sql_management_client.py new file mode 100644 index 0000000000000000000000000000000000000000..1589236977b38fbbd202c521c15ffe2e92d6202f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/_my_sql_management_client.py @@ -0,0 +1,177 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from msrest import Deserializer, Serializer + +from .. import models +from ._configuration import MySQLManagementClientConfiguration +from .operations import AdvisorsOperations, CheckNameAvailabilityOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, LocationBasedPerformanceTierOperations, LocationBasedRecommendedActionSessionsOperationStatusOperations, LocationBasedRecommendedActionSessionsResultOperations, LogFilesOperations, MySQLManagementClientOperationsMixin, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, QueryTextsOperations, RecommendedActionsOperations, RecoverableServersOperations, ReplicasOperations, ServerAdministratorsOperations, ServerBasedPerformanceTierOperations, ServerKeysOperations, ServerParametersOperations, ServerSecurityAlertPoliciesOperations, ServersOperations, TopQueryStatisticsOperations, VirtualNetworkRulesOperations, WaitStatisticsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class MySQLManagementClient(MySQLManagementClientOperationsMixin): + """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure MySQL resources including servers, databases, firewall rules, VNET rules, log files and configurations with new business model. + + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.mysql.aio.operations.ServersOperations + :ivar replicas: ReplicasOperations operations + :vartype replicas: azure.mgmt.rdbms.mysql.aio.operations.ReplicasOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.rdbms.mysql.aio.operations.FirewallRulesOperations + :ivar virtual_network_rules: VirtualNetworkRulesOperations operations + :vartype virtual_network_rules: + azure.mgmt.rdbms.mysql.aio.operations.VirtualNetworkRulesOperations + :ivar databases: DatabasesOperations operations + :vartype databases: azure.mgmt.rdbms.mysql.aio.operations.DatabasesOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: azure.mgmt.rdbms.mysql.aio.operations.ConfigurationsOperations + :ivar server_parameters: ServerParametersOperations operations + :vartype server_parameters: azure.mgmt.rdbms.mysql.aio.operations.ServerParametersOperations + :ivar log_files: LogFilesOperations operations + :vartype log_files: azure.mgmt.rdbms.mysql.aio.operations.LogFilesOperations + :ivar server_administrators: ServerAdministratorsOperations operations + :vartype server_administrators: + azure.mgmt.rdbms.mysql.aio.operations.ServerAdministratorsOperations + :ivar recoverable_servers: RecoverableServersOperations operations + :vartype recoverable_servers: + azure.mgmt.rdbms.mysql.aio.operations.RecoverableServersOperations + :ivar server_based_performance_tier: ServerBasedPerformanceTierOperations operations + :vartype server_based_performance_tier: + azure.mgmt.rdbms.mysql.aio.operations.ServerBasedPerformanceTierOperations + :ivar location_based_performance_tier: LocationBasedPerformanceTierOperations operations + :vartype location_based_performance_tier: + azure.mgmt.rdbms.mysql.aio.operations.LocationBasedPerformanceTierOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: + azure.mgmt.rdbms.mysql.aio.operations.CheckNameAvailabilityOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.mysql.aio.operations.Operations + :ivar server_security_alert_policies: ServerSecurityAlertPoliciesOperations operations + :vartype server_security_alert_policies: + azure.mgmt.rdbms.mysql.aio.operations.ServerSecurityAlertPoliciesOperations + :ivar query_texts: QueryTextsOperations operations + :vartype query_texts: azure.mgmt.rdbms.mysql.aio.operations.QueryTextsOperations + :ivar top_query_statistics: TopQueryStatisticsOperations operations + :vartype top_query_statistics: + azure.mgmt.rdbms.mysql.aio.operations.TopQueryStatisticsOperations + :ivar wait_statistics: WaitStatisticsOperations operations + :vartype wait_statistics: azure.mgmt.rdbms.mysql.aio.operations.WaitStatisticsOperations + :ivar advisors: AdvisorsOperations operations + :vartype advisors: azure.mgmt.rdbms.mysql.aio.operations.AdvisorsOperations + :ivar recommended_actions: RecommendedActionsOperations operations + :vartype recommended_actions: + azure.mgmt.rdbms.mysql.aio.operations.RecommendedActionsOperations + :ivar location_based_recommended_action_sessions_operation_status: + LocationBasedRecommendedActionSessionsOperationStatusOperations operations + :vartype location_based_recommended_action_sessions_operation_status: + azure.mgmt.rdbms.mysql.aio.operations.LocationBasedRecommendedActionSessionsOperationStatusOperations + :ivar location_based_recommended_action_sessions_result: + LocationBasedRecommendedActionSessionsResultOperations operations + :vartype location_based_recommended_action_sessions_result: + azure.mgmt.rdbms.mysql.aio.operations.LocationBasedRecommendedActionSessionsResultOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: + azure.mgmt.rdbms.mysql.aio.operations.PrivateEndpointConnectionsOperations + :ivar private_link_resources: PrivateLinkResourcesOperations operations + :vartype private_link_resources: + azure.mgmt.rdbms.mysql.aio.operations.PrivateLinkResourcesOperations + :ivar server_keys: ServerKeysOperations operations + :vartype server_keys: azure.mgmt.rdbms.mysql.aio.operations.ServerKeysOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param base_url: Service URL. Default value is 'https://management.azure.com'. + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = MySQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.servers = ServersOperations(self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations(self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.virtual_network_rules = VirtualNetworkRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations(self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.server_parameters = ServerParametersOperations(self._client, self._config, self._serialize, self._deserialize) + self.log_files = LogFilesOperations(self._client, self._config, self._serialize, self._deserialize) + self.server_administrators = ServerAdministratorsOperations(self._client, self._config, self._serialize, self._deserialize) + self.recoverable_servers = RecoverableServersOperations(self._client, self._config, self._serialize, self._deserialize) + self.server_based_performance_tier = ServerBasedPerformanceTierOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_performance_tier = LocationBasedPerformanceTierOperations(self._client, self._config, self._serialize, self._deserialize) + self.check_name_availability = CheckNameAvailabilityOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.server_security_alert_policies = ServerSecurityAlertPoliciesOperations(self._client, self._config, self._serialize, self._deserialize) + self.query_texts = QueryTextsOperations(self._client, self._config, self._serialize, self._deserialize) + self.top_query_statistics = TopQueryStatisticsOperations(self._client, self._config, self._serialize, self._deserialize) + self.wait_statistics = WaitStatisticsOperations(self._client, self._config, self._serialize, self._deserialize) + self.advisors = AdvisorsOperations(self._client, self._config, self._serialize, self._deserialize) + self.recommended_actions = RecommendedActionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_recommended_action_sessions_operation_status = LocationBasedRecommendedActionSessionsOperationStatusOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_recommended_action_sessions_result = LocationBasedRecommendedActionSessionsResultOperations(self._client, self._config, self._serialize, self._deserialize) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) + self.server_keys = ServerKeysOperations(self._client, self._config, self._serialize, self._deserialize) + + + def _send_request( + self, + request: HttpRequest, + **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "MySQLManagementClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..74e48ecd07cf36d7740246e19b7fd4a701a5130b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/_patch.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# This file is used for handwritten extensions to the generated code. Example: +# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +def patch_sdk(): + pass \ No newline at end of file diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c44d71d2baae3cc96a517fc8200c0a84cd9f350 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/__init__.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._servers_operations import ServersOperations +from ._replicas_operations import ReplicasOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._virtual_network_rules_operations import VirtualNetworkRulesOperations +from ._databases_operations import DatabasesOperations +from ._configurations_operations import ConfigurationsOperations +from ._server_parameters_operations import ServerParametersOperations +from ._log_files_operations import LogFilesOperations +from ._server_administrators_operations import ServerAdministratorsOperations +from ._recoverable_servers_operations import RecoverableServersOperations +from ._server_based_performance_tier_operations import ServerBasedPerformanceTierOperations +from ._location_based_performance_tier_operations import LocationBasedPerformanceTierOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._operations import Operations +from ._server_security_alert_policies_operations import ServerSecurityAlertPoliciesOperations +from ._query_texts_operations import QueryTextsOperations +from ._top_query_statistics_operations import TopQueryStatisticsOperations +from ._wait_statistics_operations import WaitStatisticsOperations +from ._my_sql_management_client_operations import MySQLManagementClientOperationsMixin +from ._advisors_operations import AdvisorsOperations +from ._recommended_actions_operations import RecommendedActionsOperations +from ._location_based_recommended_action_sessions_operation_status_operations import LocationBasedRecommendedActionSessionsOperationStatusOperations +from ._location_based_recommended_action_sessions_result_operations import LocationBasedRecommendedActionSessionsResultOperations +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._private_link_resources_operations import PrivateLinkResourcesOperations +from ._server_keys_operations import ServerKeysOperations + +__all__ = [ + 'ServersOperations', + 'ReplicasOperations', + 'FirewallRulesOperations', + 'VirtualNetworkRulesOperations', + 'DatabasesOperations', + 'ConfigurationsOperations', + 'ServerParametersOperations', + 'LogFilesOperations', + 'ServerAdministratorsOperations', + 'RecoverableServersOperations', + 'ServerBasedPerformanceTierOperations', + 'LocationBasedPerformanceTierOperations', + 'CheckNameAvailabilityOperations', + 'Operations', + 'ServerSecurityAlertPoliciesOperations', + 'QueryTextsOperations', + 'TopQueryStatisticsOperations', + 'WaitStatisticsOperations', + 'MySQLManagementClientOperationsMixin', + 'AdvisorsOperations', + 'RecommendedActionsOperations', + 'LocationBasedRecommendedActionSessionsOperationStatusOperations', + 'LocationBasedRecommendedActionSessionsResultOperations', + 'PrivateEndpointConnectionsOperations', + 'PrivateLinkResourcesOperations', + 'ServerKeysOperations', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_advisors_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_advisors_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..440b8a67ea3c797fd32e4da31337e0056df64de9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_advisors_operations.py @@ -0,0 +1,176 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._advisors_operations import build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class AdvisorsOperations: + """AdvisorsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + **kwargs: Any + ) -> "_models.Advisor": + """Get a recommendation action advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Advisor, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.Advisor + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Advisor"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Advisor', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.AdvisorsResultList"]: + """List recommendation action advisors. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AdvisorsResultList or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.AdvisorsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.AdvisorsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AdvisorsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_check_name_availability_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_check_name_availability_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..07c41b2c8f6067d579d025aa8b545481861cacde --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_check_name_availability_operations.py @@ -0,0 +1,97 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._check_name_availability_operations import build_execute_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class CheckNameAvailabilityOperations: + """CheckNameAvailabilityOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def execute( + self, + name_availability_request: "_models.NameAvailabilityRequest", + **kwargs: Any + ) -> "_models.NameAvailability": + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. + :type name_availability_request: ~azure.mgmt.rdbms.mysql.models.NameAvailabilityRequest + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.NameAvailability + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + + request = build_execute_request( + subscription_id=self._config.subscription_id, + content_type=content_type, + json=_json, + template_url=self.execute.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('NameAvailability', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_configurations_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_configurations_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..74e957ce46cb2cccf6348bd0909074c86da3369e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_configurations_operations.py @@ -0,0 +1,303 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._configurations_operations import build_create_or_update_request_initial, build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ConfigurationsOperations: + """ConfigurationsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> Optional["_models.Configuration"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'Configuration') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> AsyncLROPoller["_models.Configuration"]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.mysql.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Configuration or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Configuration] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Configuration', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + **kwargs: Any + ) -> "_models.Configuration": + """Gets information about a configuration of server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Configuration, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.Configuration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ConfigurationListResult"]: + """List all the configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConfigurationListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_databases_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_databases_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d3bea3a550f046fc8e5eea2585f478a65a6c50e3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_databases_operations.py @@ -0,0 +1,407 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._databases_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class DatabasesOperations: + """DatabasesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> Optional["_models.Database"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Database"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'Database') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Database', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> AsyncLROPoller["_models.Database"]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. + :type parameters: ~azure.mgmt.rdbms.mysql.models.Database + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Database or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Database] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Database', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace_async + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> "_models.Database": + """Gets information about a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Database, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.Database + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.DatabaseListResult"]: + """List all the databases in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DatabaseListResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.DatabaseListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.DatabaseListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DatabaseListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_firewall_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_firewall_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..3ca9ee3e66c369408d51022ab2e68a56e9e5c9df --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_firewall_rules_operations.py @@ -0,0 +1,408 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._firewall_rules_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class FirewallRulesOperations: + """FirewallRulesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> Optional["_models.FirewallRule"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FirewallRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'FirewallRule') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> AsyncLROPoller["_models.FirewallRule"]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. + :type parameters: ~azure.mgmt.rdbms.mysql.models.FirewallRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.FirewallRule] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('FirewallRule', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace_async + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> "_models.FirewallRule": + """Gets information about a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FirewallRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.FirewallRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.FirewallRuleListResult"]: + """List all the firewall rules in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FirewallRuleListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.FirewallRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("FirewallRuleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_location_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_location_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..aa10eaa07c1a7d23492cbf75fe867cea3dd5a427 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_location_based_performance_tier_operations.py @@ -0,0 +1,117 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._location_based_performance_tier_operations import build_list_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedPerformanceTierOperations: + """LocationBasedPerformanceTierOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + location_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PerformanceTierListResult"]: + """List all the performance tiers at specified location in a given subscription. + + :param location_name: The name of the location. + :type location_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PerformanceTierListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_operation_status_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_operation_status_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..7c1f5c781973a0d2e433b331a5c77b13ae89e550 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_operation_status_operations.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._location_based_recommended_action_sessions_operation_status_operations import build_get_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedRecommendedActionSessionsOperationStatusOperations: + """LocationBasedRecommendedActionSessionsOperationStatusOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + location_name: str, + operation_id: str, + **kwargs: Any + ) -> "_models.RecommendedActionSessionsOperationStatus": + """Recommendation action session operation status. + + :param location_name: The name of the location. + :type location_name: str + :param operation_id: The operation identifier. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecommendedActionSessionsOperationStatus, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.RecommendedActionSessionsOperationStatus + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendedActionSessionsOperationStatus"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + operation_id=operation_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecommendedActionSessionsOperationStatus', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsAzureAsyncOperation/{operationId}'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_result_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_result_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c34954a19493c70d249f789c7ad95e4d455a67 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_result_operations.py @@ -0,0 +1,122 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._location_based_recommended_action_sessions_result_operations import build_list_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedRecommendedActionSessionsResultOperations: + """LocationBasedRecommendedActionSessionsResultOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + location_name: str, + operation_id: str, + **kwargs: Any + ) -> AsyncIterable["_models.RecommendationActionsResultList"]: + """Recommendation action session operation result. + + :param location_name: The name of the location. + :type location_name: str + :param operation_id: The operation identifier. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RecommendationActionsResultList or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationActionsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationActionsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + operation_id=operation_id, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + operation_id=operation_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RecommendationActionsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsOperationResults/{operationId}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_log_files_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_log_files_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..032fa015e89ddedc99a1600eeae6bfc0418b8ea5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_log_files_operations.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._log_files_operations import build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LogFilesOperations: + """LogFilesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.LogFileListResult"]: + """List all the log files in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either LogFileListResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.LogFileListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.LogFileListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("LogFileListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/logFiles'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_my_sql_management_client_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_my_sql_management_client_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..e6a719dbf38d9e15c0177485ade6b9d37a7503e0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_my_sql_management_client_operations.py @@ -0,0 +1,186 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._my_sql_management_client_operations import build_create_recommended_action_session_request_initial, build_reset_query_performance_insight_data_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class MySQLManagementClientOperationsMixin: + + @distributed_trace_async + async def reset_query_performance_insight_data( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.QueryPerformanceInsightResetDataResult": + """Reset data for Query Performance Insight. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryPerformanceInsightResetDataResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.QueryPerformanceInsightResetDataResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryPerformanceInsightResetDataResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_reset_query_performance_insight_data_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.reset_query_performance_insight_data.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryPerformanceInsightResetDataResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + reset_query_performance_insight_data.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/resetQueryPerformanceInsightData'} # type: ignore + + + async def _create_recommended_action_session_initial( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + database_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_create_recommended_action_session_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + database_name=database_name, + template_url=self._create_recommended_action_session_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _create_recommended_action_session_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession'} # type: ignore + + + @distributed_trace_async + async def begin_create_recommended_action_session( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + database_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Create recommendation action session for the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_recommended_action_session_initial( + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_recommended_action_session.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..f9ab8fdbf4f7d3ecb2d2fa27aca670a3c06995d6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_operations.py @@ -0,0 +1,87 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class Operations: + """Operations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def list( + self, + **kwargs: Any + ) -> "_models.OperationListResult": + """Lists all of the available REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationListResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.OperationListResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_list_request( + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list.metadata = {'url': '/providers/Microsoft.DBforMySQL/operations'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_private_endpoint_connections_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_private_endpoint_connections_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..a2d6ddf2ceeb73a2d760f3cfdee33c4c0726e709 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_private_endpoint_connections_operations.py @@ -0,0 +1,532 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._private_endpoint_connections_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request, build_update_tags_request_initial +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class PrivateEndpointConnectionsOperations: + """PrivateEndpointConnectionsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> "_models.PrivateEndpointConnection": + """Gets a private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.PrivateEndpointConnection", + **kwargs: Any + ) -> Optional["_models.PrivateEndpointConnection"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.PrivateEndpointConnection"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'PrivateEndpointConnection') + + request = build_create_or_update_request_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.PrivateEndpointConnection", + **kwargs: Any + ) -> AsyncLROPoller["_models.PrivateEndpointConnection"]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: + :type parameters: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + + @distributed_trace_async + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def _update_tags_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.TagsObject", + **kwargs: Any + ) -> "_models.PrivateEndpointConnection": + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'TagsObject') + + request = build_update_tags_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + content_type=content_type, + json=_json, + template_url=self._update_tags_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _update_tags_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + + @distributed_trace_async + async def begin_update_tags( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.TagsObject", + **kwargs: Any + ) -> AsyncLROPoller["_models.PrivateEndpointConnection"]: + """Updates tags on private endpoint connection. + + Updates private endpoint connection with the specified tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: Parameters supplied to the Update private endpoint connection Tags + operation. + :type parameters: ~azure.mgmt.rdbms.mysql.models.TagsObject + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._update_tags_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PrivateEndpointConnectionListResult"]: + """Gets all private endpoint connections on a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateEndpointConnectionListResult or the result + of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnectionListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_private_link_resources_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_private_link_resources_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..5162d0ff45b098eb370896e8eb967640cd97aff7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_private_link_resources_operations.py @@ -0,0 +1,177 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._private_link_resources_operations import build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class PrivateLinkResourcesOperations: + """PrivateLinkResourcesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PrivateLinkResourceListResult"]: + """Gets the private link resources for MySQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateLinkResourceListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateLinkResourceListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources'} # type: ignore + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + group_name: str, + **kwargs: Any + ) -> "_models.PrivateLinkResource": + """Gets a private link resource for MySQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param group_name: The name of the private link resource. + :type group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateLinkResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.PrivateLinkResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + group_name=group_name, + subscription_id=self._config.subscription_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateLinkResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources/{groupName}'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_query_texts_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_query_texts_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b64df017039775968ff56db726eecc1253679dd8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_query_texts_operations.py @@ -0,0 +1,182 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, List, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._query_texts_operations import build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class QueryTextsOperations: + """QueryTextsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + query_id: str, + **kwargs: Any + ) -> "_models.QueryText": + """Retrieve the Query-Store query texts for the queryId. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_id: The Query-Store query identifier. + :type query_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryText, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.QueryText + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryText"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + query_id=query_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryText', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts/{queryId}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + query_ids: List[str], + **kwargs: Any + ) -> AsyncIterable["_models.QueryTextsResultList"]: + """Retrieve the Query-Store query texts for specified queryIds. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_ids: The query identifiers. + :type query_ids: list[str] + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either QueryTextsResultList or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.QueryTextsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryTextsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + query_ids=query_ids, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + query_ids=query_ids, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("QueryTextsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_recommended_actions_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_recommended_actions_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1dd8e765e1126ac40f8876381115c26759ff50 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_recommended_actions_operations.py @@ -0,0 +1,191 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._recommended_actions_operations import build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class RecommendedActionsOperations: + """RecommendedActionsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + recommended_action_name: str, + **kwargs: Any + ) -> "_models.RecommendationAction": + """Retrieve recommended actions from the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param recommended_action_name: The recommended action name. + :type recommended_action_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecommendationAction, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.RecommendationAction + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationAction"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + recommended_action_name=recommended_action_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecommendationAction', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + session_id: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.RecommendationActionsResultList"]: + """Retrieve recommended actions from the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param session_id: The recommendation action session identifier. + :type session_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RecommendationActionsResultList or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationActionsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationActionsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + session_id=session_id, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + session_id=session_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RecommendationActionsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_recoverable_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_recoverable_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..e02ad435d2f34ffc8ad686a7b5768f72a739d632 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_recoverable_servers_operations.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._recoverable_servers_operations import build_get_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class RecoverableServersOperations: + """RecoverableServersOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.RecoverableServerResource": + """Gets a recoverable MySQL Server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecoverableServerResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.RecoverableServerResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecoverableServerResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecoverableServerResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/recoverableServers'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_replicas_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_replicas_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b411ece15d2b3ad8c64254e6d9c0a452eb8897ad --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_replicas_operations.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._replicas_operations import build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ReplicasOperations: + """ReplicasOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the replicas for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/replicas'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_administrators_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_administrators_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..a4bcc07e3b8f121c772bf618a7c036b3a06dffe9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_administrators_operations.py @@ -0,0 +1,394 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._server_administrators_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerAdministratorsOperations: + """ServerAdministratorsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.ServerAdministratorResource": + """Gets information about a AAD server administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerAdministratorResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + properties: "_models.ServerAdministratorResource", + **kwargs: Any + ) -> "_models.ServerAdministratorResource": + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(properties, 'ServerAdministratorResource') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + properties: "_models.ServerAdministratorResource", + **kwargs: Any + ) -> AsyncLROPoller["_models.ServerAdministratorResource"]: + """Creates or update active directory administrator on an existing server. The update action will + overwrite the existing administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param properties: The required parameters for creating or updating an AAD server + administrator. + :type properties: ~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ServerAdministratorResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + properties=properties, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + + @distributed_trace_async + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes server active directory administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + @distributed_trace + def list( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerAdministratorResourceListResult"]: + """Returns a list of server Administrators. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerAdministratorResourceListResult or the + result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResourceListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResourceListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ServerAdministratorResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..74ca83bd5876657a38aaaeec2546bdcb61a0d225 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_based_performance_tier_operations.py @@ -0,0 +1,122 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._server_based_performance_tier_operations import build_list_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerBasedPerformanceTierOperations: + """ServerBasedPerformanceTierOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PerformanceTierListResult"]: + """List all the performance tiers for a MySQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PerformanceTierListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_keys_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_keys_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..4004c6b3af12a1a7232f71ac6dfa1962140f694c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_keys_operations.py @@ -0,0 +1,406 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._server_keys_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerKeysOperations: + """ServerKeysOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerKeyListResult"]: + """Gets a list of Server keys. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerKeyListResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerKeyListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKeyListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ServerKeyListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys'} # type: ignore + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + key_name: str, + **kwargs: Any + ) -> "_models.ServerKey": + """Gets a MySQL Server key. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the MySQL Server key to be retrieved. + :type key_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerKey, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.ServerKey + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + key_name=key_name, + subscription_id=self._config.subscription_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerKey', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + + async def _create_or_update_initial( + self, + server_name: str, + key_name: str, + resource_group_name: str, + parameters: "_models.ServerKey", + **kwargs: Any + ) -> "_models.ServerKey": + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerKey') + + request = build_create_or_update_request_initial( + server_name=server_name, + key_name=key_name, + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('ServerKey', pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize('ServerKey', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + + @distributed_trace_async + async def begin_create_or_update( + self, + server_name: str, + key_name: str, + resource_group_name: str, + parameters: "_models.ServerKey", + **kwargs: Any + ) -> AsyncLROPoller["_models.ServerKey"]: + """Creates or updates a MySQL Server key. + + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the MySQL Server key to be operated on (updated or created). + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param parameters: The requested MySQL Server key resource state. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerKey + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ServerKey or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerKey] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + server_name=server_name, + key_name=key_name, + resource_group_name=resource_group_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('ServerKey', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + async def _delete_initial( + self, + server_name: str, + key_name: str, + resource_group_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + server_name=server_name, + key_name=key_name, + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + + @distributed_trace_async + async def begin_delete( + self, + server_name: str, + key_name: str, + resource_group_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the MySQL Server key with the given name. + + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the MySQL Server key to be deleted. + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + server_name=server_name, + key_name=key_name, + resource_group_name=resource_group_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_parameters_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_parameters_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..cdac14d62d03c6fd3fbaa39cb14cd3ec5faf6394 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_parameters_operations.py @@ -0,0 +1,166 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._server_parameters_operations import build_list_update_configurations_request_initial +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerParametersOperations: + """ServerParametersOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _list_update_configurations_initial( + self, + resource_group_name: str, + server_name: str, + value: "_models.ConfigurationListResult", + **kwargs: Any + ) -> Optional["_models.ConfigurationListResult"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ConfigurationListResult"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(value, 'ConfigurationListResult') + + request = build_list_update_configurations_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._list_update_configurations_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _list_update_configurations_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations'} # type: ignore + + + @distributed_trace_async + async def begin_list_update_configurations( + self, + resource_group_name: str, + server_name: str, + value: "_models.ConfigurationListResult", + **kwargs: Any + ) -> AsyncLROPoller["_models.ConfigurationListResult"]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param value: The parameters for updating a list of server configuration. + :type value: ~azure.mgmt.rdbms.mysql.models.ConfigurationListResult + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ConfigurationListResult or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._list_update_configurations_initial( + resource_group_name=resource_group_name, + server_name=server_name, + value=value, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_list_update_configurations.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_security_alert_policies_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_security_alert_policies_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..16160418771e376dcae4965aa833c3c2bcd9c4bd --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_server_security_alert_policies_operations.py @@ -0,0 +1,304 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._server_security_alert_policies_operations import build_create_or_update_request_initial, build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerSecurityAlertPoliciesOperations: + """ServerSecurityAlertPoliciesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + **kwargs: Any + ) -> "_models.ServerSecurityAlertPolicy": + """Get a server's security alert policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the security alert policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerSecurityAlertPolicy, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + security_alert_policy_name=security_alert_policy_name, + subscription_id=self._config.subscription_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + parameters: "_models.ServerSecurityAlertPolicy", + **kwargs: Any + ) -> Optional["_models.ServerSecurityAlertPolicy"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ServerSecurityAlertPolicy"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerSecurityAlertPolicy') + + request = build_create_or_update_request_initial( + resource_group_name=resource_group_name, + server_name=server_name, + security_alert_policy_name=security_alert_policy_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + parameters: "_models.ServerSecurityAlertPolicy", + **kwargs: Any + ) -> AsyncLROPoller["_models.ServerSecurityAlertPolicy"]: + """Creates or updates a threat detection policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the threat detection policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ServerSecurityAlertPolicy or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + security_alert_policy_name=security_alert_policy_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerSecurityAlertPolicyListResult"]: + """Get the server's threat detection policies. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerSecurityAlertPolicyListResult or the result + of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicyListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicyListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ServerSecurityAlertPolicyListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..06ce95e7c4e5d5e6040c2a5e668a631ff806e883 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_servers_operations.py @@ -0,0 +1,966 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._servers_operations import build_create_request_initial, build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_request, build_restart_request_initial, build_start_request_initial, build_stop_request_initial, build_update_request_initial, build_upgrade_request_initial +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServersOperations: + """ServersOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForCreate", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerForCreate') + + request = build_create_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._create_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + + @distributed_trace_async + async def begin_create( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForCreate", + **kwargs: Any + ) -> AsyncLROPoller["_models.Server"]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerForCreate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Server', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + async def _update_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpdateParameters", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerUpdateParameters') + + request = build_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpdateParameters", + **kwargs: Any + ) -> AsyncLROPoller["_models.Server"]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpdateParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Server', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + + @distributed_trace_async + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.Server": + """Gets information about a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Server, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.Server + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + + @distributed_trace + def list_by_resource_group( + self, + resource_group_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the servers in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + template_url=self.list_by_resource_group.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers'} # type: ignore + + @distributed_trace + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the servers in a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/servers'} # type: ignore + + async def _restart_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_restart_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._restart_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart'} # type: ignore + + + @distributed_trace_async + async def begin_restart( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._restart_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart'} # type: ignore + + async def _start_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_start_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._start_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start'} # type: ignore + + + @distributed_trace_async + async def begin_start( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Starts a stopped server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._start_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start'} # type: ignore + + async def _stop_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_stop_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._stop_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _stop_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop'} # type: ignore + + + @distributed_trace_async + async def begin_stop( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Stops a running server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._stop_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop'} # type: ignore + + async def _upgrade_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpgradeParameters", + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerUpgradeParameters') + + request = build_upgrade_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._upgrade_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _upgrade_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade'} # type: ignore + + + @distributed_trace_async + async def begin_upgrade( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpgradeParameters", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Upgrade server version. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpgradeParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._upgrade_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_upgrade.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_top_query_statistics_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_top_query_statistics_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..e163c16399302e0a0f5ea7bd323e12c38c522363 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_top_query_statistics_operations.py @@ -0,0 +1,188 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._top_query_statistics_operations import build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class TopQueryStatisticsOperations: + """TopQueryStatisticsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + query_statistic_id: str, + **kwargs: Any + ) -> "_models.QueryStatistic": + """Retrieve the query statistic for specified identifier. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_statistic_id: The Query Statistic identifier. + :type query_statistic_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryStatistic, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.QueryStatistic + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryStatistic"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + query_statistic_id=query_statistic_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryStatistic', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics/{queryStatisticId}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.TopQueryStatisticsInput", + **kwargs: Any + ) -> AsyncIterable["_models.TopQueryStatisticsResultList"]: + """Retrieve the Query-Store top queries for specified metric and aggregation. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for retrieving top query statistics. + :type parameters: ~azure.mgmt.rdbms.mysql.models.TopQueryStatisticsInput + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either TopQueryStatisticsResultList or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.TopQueryStatisticsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + cls = kwargs.pop('cls', None) # type: ClsType["_models.TopQueryStatisticsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + _json = self._serialize.body(parameters, 'TopQueryStatisticsInput') + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + _json = self._serialize.body(parameters, 'TopQueryStatisticsInput') + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("TopQueryStatisticsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_virtual_network_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_virtual_network_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..10b68a807a542010469aa8b7741a2cac426c931e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_virtual_network_rules_operations.py @@ -0,0 +1,408 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._virtual_network_rules_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class VirtualNetworkRulesOperations: + """VirtualNetworkRulesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> "_models.VirtualNetworkRule": + """Gets a virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + virtual_network_rule_name=virtual_network_rule_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: "_models.VirtualNetworkRule", + **kwargs: Any + ) -> Optional["_models.VirtualNetworkRule"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.VirtualNetworkRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'VirtualNetworkRule') + + request = build_create_or_update_request_initial( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + virtual_network_rule_name=virtual_network_rule_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: "_models.VirtualNetworkRule", + **kwargs: Any + ) -> AsyncLROPoller["_models.VirtualNetworkRule"]: + """Creates or updates an existing virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :param parameters: The requested virtual Network Rule Resource state. + :type parameters: ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either VirtualNetworkRule or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + subscription_id=self._config.subscription_id, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + + @distributed_trace_async + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the virtual network rule with the given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.VirtualNetworkRuleListResult"]: + """Gets a list of virtual network rules in a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either VirtualNetworkRuleListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("VirtualNetworkRuleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_wait_statistics_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_wait_statistics_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..22845108a08aee36c59909d5698886e8338d158c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/aio/operations/_wait_statistics_operations.py @@ -0,0 +1,188 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._wait_statistics_operations import build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class WaitStatisticsOperations: + """WaitStatisticsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + wait_statistics_id: str, + **kwargs: Any + ) -> "_models.WaitStatistic": + """Retrieve wait statistics for specified identifier. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param wait_statistics_id: The Wait Statistic identifier. + :type wait_statistics_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: WaitStatistic, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.WaitStatistic + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.WaitStatistic"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + wait_statistics_id=wait_statistics_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('WaitStatistic', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics/{waitStatisticsId}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.WaitStatisticsInput", + **kwargs: Any + ) -> AsyncIterable["_models.WaitStatisticsResultList"]: + """Retrieve wait statistics for specified aggregation window. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for retrieving wait statistics. + :type parameters: ~azure.mgmt.rdbms.mysql.models.WaitStatisticsInput + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either WaitStatisticsResultList or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.WaitStatisticsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + cls = kwargs.pop('cls', None) # type: ClsType["_models.WaitStatisticsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + _json = self._serialize.body(parameters, 'WaitStatisticsInput') + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + _json = self._serialize.body(parameters, 'WaitStatisticsInput') + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("WaitStatisticsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2708af3f4eb8b3aaa784925401a6d47ad24e6e9f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/models/__init__.py @@ -0,0 +1,193 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import Advisor +from ._models_py3 import AdvisorsResultList +from ._models_py3 import CloudErrorAutoGenerated +from ._models_py3 import Configuration +from ._models_py3 import ConfigurationListResult +from ._models_py3 import Database +from ._models_py3 import DatabaseListResult +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorResponse +from ._models_py3 import FirewallRule +from ._models_py3 import FirewallRuleListResult +from ._models_py3 import LogFile +from ._models_py3 import LogFileListResult +from ._models_py3 import NameAvailability +from ._models_py3 import NameAvailabilityRequest +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import PerformanceTierListResult +from ._models_py3 import PerformanceTierProperties +from ._models_py3 import PerformanceTierServiceLevelObjectives +from ._models_py3 import PrivateEndpointConnection +from ._models_py3 import PrivateEndpointConnectionListResult +from ._models_py3 import PrivateEndpointProperty +from ._models_py3 import PrivateLinkResource +from ._models_py3 import PrivateLinkResourceListResult +from ._models_py3 import PrivateLinkResourceProperties +from ._models_py3 import PrivateLinkServiceConnectionStateProperty +from ._models_py3 import ProxyResource +from ._models_py3 import QueryPerformanceInsightResetDataResult +from ._models_py3 import QueryStatistic +from ._models_py3 import QueryText +from ._models_py3 import QueryTextsResultList +from ._models_py3 import RecommendationAction +from ._models_py3 import RecommendationActionsResultList +from ._models_py3 import RecommendedActionSessionsOperationStatus +from ._models_py3 import RecoverableServerResource +from ._models_py3 import Resource +from ._models_py3 import ResourceIdentity +from ._models_py3 import Server +from ._models_py3 import ServerAdministratorResource +from ._models_py3 import ServerAdministratorResourceListResult +from ._models_py3 import ServerForCreate +from ._models_py3 import ServerKey +from ._models_py3 import ServerKeyListResult +from ._models_py3 import ServerListResult +from ._models_py3 import ServerPrivateEndpointConnection +from ._models_py3 import ServerPrivateEndpointConnectionProperties +from ._models_py3 import ServerPrivateLinkServiceConnectionStateProperty +from ._models_py3 import ServerPropertiesForCreate +from ._models_py3 import ServerPropertiesForDefaultCreate +from ._models_py3 import ServerPropertiesForGeoRestore +from ._models_py3 import ServerPropertiesForReplica +from ._models_py3 import ServerPropertiesForRestore +from ._models_py3 import ServerSecurityAlertPolicy +from ._models_py3 import ServerSecurityAlertPolicyListResult +from ._models_py3 import ServerUpdateParameters +from ._models_py3 import ServerUpgradeParameters +from ._models_py3 import Sku +from ._models_py3 import StorageProfile +from ._models_py3 import TagsObject +from ._models_py3 import TopQueryStatisticsInput +from ._models_py3 import TopQueryStatisticsResultList +from ._models_py3 import TrackedResource +from ._models_py3 import VirtualNetworkRule +from ._models_py3 import VirtualNetworkRuleListResult +from ._models_py3 import WaitStatistic +from ._models_py3 import WaitStatisticsInput +from ._models_py3 import WaitStatisticsResultList + + +from ._my_sql_management_client_enums import ( + CreateMode, + GeoRedundantBackup, + IdentityType, + InfrastructureEncryption, + MinimalTlsVersionEnum, + OperationOrigin, + PrivateEndpointProvisioningState, + PrivateLinkServiceConnectionStateActionsRequire, + PrivateLinkServiceConnectionStateStatus, + PublicNetworkAccessEnum, + QueryPerformanceInsightResetDataResultState, + SecurityAlertPolicyName, + ServerKeyType, + ServerSecurityAlertPolicyState, + ServerState, + ServerVersion, + SkuTier, + SslEnforcementEnum, + StorageAutogrow, + VirtualNetworkRuleState, +) + +__all__ = [ + 'Advisor', + 'AdvisorsResultList', + 'CloudErrorAutoGenerated', + 'Configuration', + 'ConfigurationListResult', + 'Database', + 'DatabaseListResult', + 'ErrorAdditionalInfo', + 'ErrorResponse', + 'FirewallRule', + 'FirewallRuleListResult', + 'LogFile', + 'LogFileListResult', + 'NameAvailability', + 'NameAvailabilityRequest', + 'Operation', + 'OperationDisplay', + 'OperationListResult', + 'PerformanceTierListResult', + 'PerformanceTierProperties', + 'PerformanceTierServiceLevelObjectives', + 'PrivateEndpointConnection', + 'PrivateEndpointConnectionListResult', + 'PrivateEndpointProperty', + 'PrivateLinkResource', + 'PrivateLinkResourceListResult', + 'PrivateLinkResourceProperties', + 'PrivateLinkServiceConnectionStateProperty', + 'ProxyResource', + 'QueryPerformanceInsightResetDataResult', + 'QueryStatistic', + 'QueryText', + 'QueryTextsResultList', + 'RecommendationAction', + 'RecommendationActionsResultList', + 'RecommendedActionSessionsOperationStatus', + 'RecoverableServerResource', + 'Resource', + 'ResourceIdentity', + 'Server', + 'ServerAdministratorResource', + 'ServerAdministratorResourceListResult', + 'ServerForCreate', + 'ServerKey', + 'ServerKeyListResult', + 'ServerListResult', + 'ServerPrivateEndpointConnection', + 'ServerPrivateEndpointConnectionProperties', + 'ServerPrivateLinkServiceConnectionStateProperty', + 'ServerPropertiesForCreate', + 'ServerPropertiesForDefaultCreate', + 'ServerPropertiesForGeoRestore', + 'ServerPropertiesForReplica', + 'ServerPropertiesForRestore', + 'ServerSecurityAlertPolicy', + 'ServerSecurityAlertPolicyListResult', + 'ServerUpdateParameters', + 'ServerUpgradeParameters', + 'Sku', + 'StorageProfile', + 'TagsObject', + 'TopQueryStatisticsInput', + 'TopQueryStatisticsResultList', + 'TrackedResource', + 'VirtualNetworkRule', + 'VirtualNetworkRuleListResult', + 'WaitStatistic', + 'WaitStatisticsInput', + 'WaitStatisticsResultList', + 'CreateMode', + 'GeoRedundantBackup', + 'IdentityType', + 'InfrastructureEncryption', + 'MinimalTlsVersionEnum', + 'OperationOrigin', + 'PrivateEndpointProvisioningState', + 'PrivateLinkServiceConnectionStateActionsRequire', + 'PrivateLinkServiceConnectionStateStatus', + 'PublicNetworkAccessEnum', + 'QueryPerformanceInsightResetDataResultState', + 'SecurityAlertPolicyName', + 'ServerKeyType', + 'ServerSecurityAlertPolicyState', + 'ServerState', + 'ServerVersion', + 'SkuTier', + 'SslEnforcementEnum', + 'StorageAutogrow', + 'VirtualNetworkRuleState', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..975762b3a44ce5999bec915d3cefbc173bdfac16 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/models/_models_py3.py @@ -0,0 +1,3615 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import Any, Dict, List, Optional, Union + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + +from ._my_sql_management_client_enums import * + + +class Resource(msrest.serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(ProxyResource, self).__init__(**kwargs) + + +class Advisor(ProxyResource): + """Represents a recommendation action advisor. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar properties: The properties of a recommendation action advisor. + :vartype properties: any + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'object'}, + } + + def __init__( + self, + *, + properties: Optional[Any] = None, + **kwargs + ): + """ + :keyword properties: The properties of a recommendation action advisor. + :paramtype properties: any + """ + super(Advisor, self).__init__(**kwargs) + self.properties = properties + + +class AdvisorsResultList(msrest.serialization.Model): + """A list of query statistics. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of recommendation action advisors. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.Advisor] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Advisor]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(AdvisorsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class CloudErrorAutoGenerated(msrest.serialization.Model): + """An error response from the Batch service. + + :ivar error: Error message. + :vartype error: ~azure.mgmt.rdbms.mysql.models.ErrorResponse + """ + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorResponse'}, + } + + def __init__( + self, + *, + error: Optional["ErrorResponse"] = None, + **kwargs + ): + """ + :keyword error: Error message. + :paramtype error: ~azure.mgmt.rdbms.mysql.models.ErrorResponse + """ + super(CloudErrorAutoGenerated, self).__init__(**kwargs) + self.error = error + + +class Configuration(ProxyResource): + """Represents a Configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar value: Value of the configuration. + :vartype value: str + :ivar description: Description of the configuration. + :vartype description: str + :ivar default_value: Default value of the configuration. + :vartype default_value: str + :ivar data_type: Data type of the configuration. + :vartype data_type: str + :ivar allowed_values: Allowed values of the configuration. + :vartype allowed_values: str + :ivar source: Source of the configuration. + :vartype source: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'description': {'readonly': True}, + 'default_value': {'readonly': True}, + 'data_type': {'readonly': True}, + 'allowed_values': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'value': {'key': 'properties.value', 'type': 'str'}, + 'description': {'key': 'properties.description', 'type': 'str'}, + 'default_value': {'key': 'properties.defaultValue', 'type': 'str'}, + 'data_type': {'key': 'properties.dataType', 'type': 'str'}, + 'allowed_values': {'key': 'properties.allowedValues', 'type': 'str'}, + 'source': {'key': 'properties.source', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[str] = None, + source: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Value of the configuration. + :paramtype value: str + :keyword source: Source of the configuration. + :paramtype source: str + """ + super(Configuration, self).__init__(**kwargs) + self.value = value + self.description = None + self.default_value = None + self.data_type = None + self.allowed_values = None + self.source = source + + +class ConfigurationListResult(msrest.serialization.Model): + """A list of server configurations. + + :ivar value: The list of server configurations. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.Configuration] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Configuration]'}, + } + + def __init__( + self, + *, + value: Optional[List["Configuration"]] = None, + **kwargs + ): + """ + :keyword value: The list of server configurations. + :paramtype value: list[~azure.mgmt.rdbms.mysql.models.Configuration] + """ + super(ConfigurationListResult, self).__init__(**kwargs) + self.value = value + + +class Database(ProxyResource): + """Represents a Database. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar charset: The charset of the database. + :vartype charset: str + :ivar collation: The collation of the database. + :vartype collation: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'charset': {'key': 'properties.charset', 'type': 'str'}, + 'collation': {'key': 'properties.collation', 'type': 'str'}, + } + + def __init__( + self, + *, + charset: Optional[str] = None, + collation: Optional[str] = None, + **kwargs + ): + """ + :keyword charset: The charset of the database. + :paramtype charset: str + :keyword collation: The collation of the database. + :paramtype collation: str + """ + super(Database, self).__init__(**kwargs) + self.charset = charset + self.collation = collation + + +class DatabaseListResult(msrest.serialization.Model): + """A List of databases. + + :ivar value: The list of databases housed in a server. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.Database] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Database]'}, + } + + def __init__( + self, + *, + value: Optional[List["Database"]] = None, + **kwargs + ): + """ + :keyword value: The list of databases housed in a server. + :paramtype value: list[~azure.mgmt.rdbms.mysql.models.Database] + """ + super(DatabaseListResult, self).__init__(**kwargs) + self.value = value + + +class ErrorAdditionalInfo(msrest.serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorResponse(msrest.serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.rdbms.mysql.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.rdbms.mysql.models.ErrorAdditionalInfo] + """ + + _validation = { + 'code': {'readonly': True}, + 'message': {'readonly': True}, + 'target': {'readonly': True}, + 'details': {'readonly': True}, + 'additional_info': {'readonly': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'target': {'key': 'target', 'type': 'str'}, + 'details': {'key': 'details', 'type': '[ErrorResponse]'}, + 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(ErrorResponse, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class FirewallRule(ProxyResource): + """Represents a server firewall rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar start_ip_address: Required. The start IP address of the server firewall rule. Must be + IPv4 format. + :vartype start_ip_address: str + :ivar end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 + format. + :vartype end_ip_address: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'start_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + 'end_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'start_ip_address': {'key': 'properties.startIpAddress', 'type': 'str'}, + 'end_ip_address': {'key': 'properties.endIpAddress', 'type': 'str'}, + } + + def __init__( + self, + *, + start_ip_address: str, + end_ip_address: str, + **kwargs + ): + """ + :keyword start_ip_address: Required. The start IP address of the server firewall rule. Must be + IPv4 format. + :paramtype start_ip_address: str + :keyword end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 + format. + :paramtype end_ip_address: str + """ + super(FirewallRule, self).__init__(**kwargs) + self.start_ip_address = start_ip_address + self.end_ip_address = end_ip_address + + +class FirewallRuleListResult(msrest.serialization.Model): + """A list of firewall rules. + + :ivar value: The list of firewall rules in a server. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.FirewallRule] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FirewallRule]'}, + } + + def __init__( + self, + *, + value: Optional[List["FirewallRule"]] = None, + **kwargs + ): + """ + :keyword value: The list of firewall rules in a server. + :paramtype value: list[~azure.mgmt.rdbms.mysql.models.FirewallRule] + """ + super(FirewallRuleListResult, self).__init__(**kwargs) + self.value = value + + +class LogFile(ProxyResource): + """Represents a log file. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar size_in_kb: Size of the log file. + :vartype size_in_kb: long + :ivar created_time: Creation timestamp of the log file. + :vartype created_time: ~datetime.datetime + :ivar last_modified_time: Last modified timestamp of the log file. + :vartype last_modified_time: ~datetime.datetime + :ivar type_properties_type: Type of the log file. + :vartype type_properties_type: str + :ivar url: The url to download the log file from. + :vartype url: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'created_time': {'readonly': True}, + 'last_modified_time': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'size_in_kb': {'key': 'properties.sizeInKB', 'type': 'long'}, + 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, + 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'iso-8601'}, + 'type_properties_type': {'key': 'properties.type', 'type': 'str'}, + 'url': {'key': 'properties.url', 'type': 'str'}, + } + + def __init__( + self, + *, + size_in_kb: Optional[int] = None, + type_properties_type: Optional[str] = None, + url: Optional[str] = None, + **kwargs + ): + """ + :keyword size_in_kb: Size of the log file. + :paramtype size_in_kb: long + :keyword type_properties_type: Type of the log file. + :paramtype type_properties_type: str + :keyword url: The url to download the log file from. + :paramtype url: str + """ + super(LogFile, self).__init__(**kwargs) + self.size_in_kb = size_in_kb + self.created_time = None + self.last_modified_time = None + self.type_properties_type = type_properties_type + self.url = url + + +class LogFileListResult(msrest.serialization.Model): + """A list of log files. + + :ivar value: The list of log files. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.LogFile] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[LogFile]'}, + } + + def __init__( + self, + *, + value: Optional[List["LogFile"]] = None, + **kwargs + ): + """ + :keyword value: The list of log files. + :paramtype value: list[~azure.mgmt.rdbms.mysql.models.LogFile] + """ + super(LogFileListResult, self).__init__(**kwargs) + self.value = value + + +class NameAvailability(msrest.serialization.Model): + """Represents a resource name availability. + + :ivar message: Error Message. + :vartype message: str + :ivar name_available: Indicates whether the resource name is available. + :vartype name_available: bool + :ivar reason: Reason for name being unavailable. + :vartype reason: str + """ + + _attribute_map = { + 'message': {'key': 'message', 'type': 'str'}, + 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, + 'reason': {'key': 'reason', 'type': 'str'}, + } + + def __init__( + self, + *, + message: Optional[str] = None, + name_available: Optional[bool] = None, + reason: Optional[str] = None, + **kwargs + ): + """ + :keyword message: Error Message. + :paramtype message: str + :keyword name_available: Indicates whether the resource name is available. + :paramtype name_available: bool + :keyword reason: Reason for name being unavailable. + :paramtype reason: str + """ + super(NameAvailability, self).__init__(**kwargs) + self.message = message + self.name_available = name_available + self.reason = reason + + +class NameAvailabilityRequest(msrest.serialization.Model): + """Request from client to check resource name availability. + + All required parameters must be populated in order to send to Azure. + + :ivar name: Required. Resource name to verify. + :vartype name: str + :ivar type: Resource type used for verification. + :vartype type: str + """ + + _validation = { + 'name': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + name: str, + type: Optional[str] = None, + **kwargs + ): + """ + :keyword name: Required. Resource name to verify. + :paramtype name: str + :keyword type: Resource type used for verification. + :paramtype type: str + """ + super(NameAvailabilityRequest, self).__init__(**kwargs) + self.name = name + self.type = type + + +class Operation(msrest.serialization.Model): + """REST API operation definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation being performed on this particular object. + :vartype name: str + :ivar display: The localized display information for this particular operation or action. + :vartype display: ~azure.mgmt.rdbms.mysql.models.OperationDisplay + :ivar origin: The intended executor of the operation. Possible values include: "NotSpecified", + "user", "system". + :vartype origin: str or ~azure.mgmt.rdbms.mysql.models.OperationOrigin + :ivar properties: Additional descriptions for the operation. + :vartype properties: dict[str, any] + """ + + _validation = { + 'name': {'readonly': True}, + 'display': {'readonly': True}, + 'origin': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'OperationDisplay'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{object}'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(Operation, self).__init__(**kwargs) + self.name = None + self.display = None + self.origin = None + self.properties = None + + +class OperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: Operation resource provider name. + :vartype provider: str + :ivar resource: Resource on which the operation is performed. + :vartype resource: str + :ivar operation: Localized friendly name for the operation. + :vartype operation: str + :ivar description: Operation description. + :vartype description: str + """ + + _validation = { + 'provider': {'readonly': True}, + 'resource': {'readonly': True}, + 'operation': {'readonly': True}, + 'description': {'readonly': True}, + } + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(OperationDisplay, self).__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(msrest.serialization.Model): + """A list of resource provider operations. + + :ivar value: The list of resource provider operations. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.Operation] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Operation]'}, + } + + def __init__( + self, + *, + value: Optional[List["Operation"]] = None, + **kwargs + ): + """ + :keyword value: The list of resource provider operations. + :paramtype value: list[~azure.mgmt.rdbms.mysql.models.Operation] + """ + super(OperationListResult, self).__init__(**kwargs) + self.value = value + + +class PerformanceTierListResult(msrest.serialization.Model): + """A list of performance tiers. + + :ivar value: The list of performance tiers. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.PerformanceTierProperties] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PerformanceTierProperties]'}, + } + + def __init__( + self, + *, + value: Optional[List["PerformanceTierProperties"]] = None, + **kwargs + ): + """ + :keyword value: The list of performance tiers. + :paramtype value: list[~azure.mgmt.rdbms.mysql.models.PerformanceTierProperties] + """ + super(PerformanceTierListResult, self).__init__(**kwargs) + self.value = value + + +class PerformanceTierProperties(msrest.serialization.Model): + """Performance tier properties. + + :ivar id: ID of the performance tier. + :vartype id: str + :ivar max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :vartype max_backup_retention_days: int + :ivar min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :vartype min_backup_retention_days: int + :ivar max_storage_mb: Max storage allowed for a server. + :vartype max_storage_mb: int + :ivar min_large_storage_mb: Max storage allowed for a server. + :vartype min_large_storage_mb: int + :ivar max_large_storage_mb: Max storage allowed for a server. + :vartype max_large_storage_mb: int + :ivar min_storage_mb: Max storage allowed for a server. + :vartype min_storage_mb: int + :ivar service_level_objectives: Service level objectives associated with the performance tier. + :vartype service_level_objectives: + list[~azure.mgmt.rdbms.mysql.models.PerformanceTierServiceLevelObjectives] + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, + 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, + 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, + 'min_large_storage_mb': {'key': 'minLargeStorageMB', 'type': 'int'}, + 'max_large_storage_mb': {'key': 'maxLargeStorageMB', 'type': 'int'}, + 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, + 'service_level_objectives': {'key': 'serviceLevelObjectives', 'type': '[PerformanceTierServiceLevelObjectives]'}, + } + + def __init__( + self, + *, + id: Optional[str] = None, + max_backup_retention_days: Optional[int] = None, + min_backup_retention_days: Optional[int] = None, + max_storage_mb: Optional[int] = None, + min_large_storage_mb: Optional[int] = None, + max_large_storage_mb: Optional[int] = None, + min_storage_mb: Optional[int] = None, + service_level_objectives: Optional[List["PerformanceTierServiceLevelObjectives"]] = None, + **kwargs + ): + """ + :keyword id: ID of the performance tier. + :paramtype id: str + :keyword max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :paramtype max_backup_retention_days: int + :keyword min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :paramtype min_backup_retention_days: int + :keyword max_storage_mb: Max storage allowed for a server. + :paramtype max_storage_mb: int + :keyword min_large_storage_mb: Max storage allowed for a server. + :paramtype min_large_storage_mb: int + :keyword max_large_storage_mb: Max storage allowed for a server. + :paramtype max_large_storage_mb: int + :keyword min_storage_mb: Max storage allowed for a server. + :paramtype min_storage_mb: int + :keyword service_level_objectives: Service level objectives associated with the performance + tier. + :paramtype service_level_objectives: + list[~azure.mgmt.rdbms.mysql.models.PerformanceTierServiceLevelObjectives] + """ + super(PerformanceTierProperties, self).__init__(**kwargs) + self.id = id + self.max_backup_retention_days = max_backup_retention_days + self.min_backup_retention_days = min_backup_retention_days + self.max_storage_mb = max_storage_mb + self.min_large_storage_mb = min_large_storage_mb + self.max_large_storage_mb = max_large_storage_mb + self.min_storage_mb = min_storage_mb + self.service_level_objectives = service_level_objectives + + +class PerformanceTierServiceLevelObjectives(msrest.serialization.Model): + """Service level objectives for performance tier. + + :ivar id: ID for the service level objective. + :vartype id: str + :ivar edition: Edition of the performance tier. + :vartype edition: str + :ivar v_core: vCore associated with the service level objective. + :vartype v_core: int + :ivar hardware_generation: Hardware generation associated with the service level objective. + :vartype hardware_generation: str + :ivar max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :vartype max_backup_retention_days: int + :ivar min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :vartype min_backup_retention_days: int + :ivar max_storage_mb: Max storage allowed for a server. + :vartype max_storage_mb: int + :ivar min_storage_mb: Max storage allowed for a server. + :vartype min_storage_mb: int + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'edition': {'key': 'edition', 'type': 'str'}, + 'v_core': {'key': 'vCore', 'type': 'int'}, + 'hardware_generation': {'key': 'hardwareGeneration', 'type': 'str'}, + 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, + 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, + 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, + 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, + } + + def __init__( + self, + *, + id: Optional[str] = None, + edition: Optional[str] = None, + v_core: Optional[int] = None, + hardware_generation: Optional[str] = None, + max_backup_retention_days: Optional[int] = None, + min_backup_retention_days: Optional[int] = None, + max_storage_mb: Optional[int] = None, + min_storage_mb: Optional[int] = None, + **kwargs + ): + """ + :keyword id: ID for the service level objective. + :paramtype id: str + :keyword edition: Edition of the performance tier. + :paramtype edition: str + :keyword v_core: vCore associated with the service level objective. + :paramtype v_core: int + :keyword hardware_generation: Hardware generation associated with the service level objective. + :paramtype hardware_generation: str + :keyword max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :paramtype max_backup_retention_days: int + :keyword min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :paramtype min_backup_retention_days: int + :keyword max_storage_mb: Max storage allowed for a server. + :paramtype max_storage_mb: int + :keyword min_storage_mb: Max storage allowed for a server. + :paramtype min_storage_mb: int + """ + super(PerformanceTierServiceLevelObjectives, self).__init__(**kwargs) + self.id = id + self.edition = edition + self.v_core = v_core + self.hardware_generation = hardware_generation + self.max_backup_retention_days = max_backup_retention_days + self.min_backup_retention_days = min_backup_retention_days + self.max_storage_mb = max_storage_mb + self.min_storage_mb = min_storage_mb + + +class PrivateEndpointConnection(ProxyResource): + """A private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar private_endpoint: Private endpoint which the connection belongs to. + :vartype private_endpoint: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointProperty + :ivar private_link_service_connection_state: Connection state of the private endpoint + connection. + :vartype private_link_service_connection_state: + ~azure.mgmt.rdbms.mysql.models.PrivateLinkServiceConnectionStateProperty + :ivar provisioning_state: State of the private endpoint connection. + :vartype provisioning_state: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpointProperty'}, + 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionStateProperty'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + } + + def __init__( + self, + *, + private_endpoint: Optional["PrivateEndpointProperty"] = None, + private_link_service_connection_state: Optional["PrivateLinkServiceConnectionStateProperty"] = None, + **kwargs + ): + """ + :keyword private_endpoint: Private endpoint which the connection belongs to. + :paramtype private_endpoint: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointProperty + :keyword private_link_service_connection_state: Connection state of the private endpoint + connection. + :paramtype private_link_service_connection_state: + ~azure.mgmt.rdbms.mysql.models.PrivateLinkServiceConnectionStateProperty + """ + super(PrivateEndpointConnection, self).__init__(**kwargs) + self.private_endpoint = private_endpoint + self.private_link_service_connection_state = private_link_service_connection_state + self.provisioning_state = None + + +class PrivateEndpointConnectionListResult(msrest.serialization.Model): + """A list of private endpoint connections. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PrivateEndpointConnection]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(PrivateEndpointConnectionListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class PrivateEndpointProperty(msrest.serialization.Model): + """PrivateEndpointProperty. + + :ivar id: Resource id of the private endpoint. + :vartype id: str + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + } + + def __init__( + self, + *, + id: Optional[str] = None, + **kwargs + ): + """ + :keyword id: Resource id of the private endpoint. + :paramtype id: str + """ + super(PrivateEndpointProperty, self).__init__(**kwargs) + self.id = id + + +class PrivateLinkResource(ProxyResource): + """A private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar properties: The private link resource group id. + :vartype properties: ~azure.mgmt.rdbms.mysql.models.PrivateLinkResourceProperties + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'PrivateLinkResourceProperties'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(PrivateLinkResource, self).__init__(**kwargs) + self.properties = None + + +class PrivateLinkResourceListResult(msrest.serialization.Model): + """A list of private link resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.PrivateLinkResource] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PrivateLinkResource]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(PrivateLinkResourceListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class PrivateLinkResourceProperties(msrest.serialization.Model): + """Properties of a private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar group_id: The private link resource group id. + :vartype group_id: str + :ivar required_members: The private link resource required member names. + :vartype required_members: list[str] + """ + + _validation = { + 'group_id': {'readonly': True}, + 'required_members': {'readonly': True}, + } + + _attribute_map = { + 'group_id': {'key': 'groupId', 'type': 'str'}, + 'required_members': {'key': 'requiredMembers', 'type': '[str]'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(PrivateLinkResourceProperties, self).__init__(**kwargs) + self.group_id = None + self.required_members = None + + +class PrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): + """PrivateLinkServiceConnectionStateProperty. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar status: Required. The private link service connection status. + :vartype status: str + :ivar description: Required. The private link service connection description. + :vartype description: str + :ivar actions_required: The actions required for private link service connection. + :vartype actions_required: str + """ + + _validation = { + 'status': {'required': True}, + 'description': {'required': True}, + 'actions_required': {'readonly': True}, + } + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + } + + def __init__( + self, + *, + status: str, + description: str, + **kwargs + ): + """ + :keyword status: Required. The private link service connection status. + :paramtype status: str + :keyword description: Required. The private link service connection description. + :paramtype description: str + """ + super(PrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + self.status = status + self.description = description + self.actions_required = None + + +class QueryPerformanceInsightResetDataResult(msrest.serialization.Model): + """Result of Query Performance Insight data reset. + + :ivar status: Indicates result of the operation. Possible values include: "Succeeded", + "Failed". + :vartype status: str or + ~azure.mgmt.rdbms.mysql.models.QueryPerformanceInsightResetDataResultState + :ivar message: operation message. + :vartype message: str + """ + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__( + self, + *, + status: Optional[Union[str, "QueryPerformanceInsightResetDataResultState"]] = None, + message: Optional[str] = None, + **kwargs + ): + """ + :keyword status: Indicates result of the operation. Possible values include: "Succeeded", + "Failed". + :paramtype status: str or + ~azure.mgmt.rdbms.mysql.models.QueryPerformanceInsightResetDataResultState + :keyword message: operation message. + :paramtype message: str + """ + super(QueryPerformanceInsightResetDataResult, self).__init__(**kwargs) + self.status = status + self.message = message + + +class QueryStatistic(ProxyResource): + """Represents a Query Statistic. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar query_id: Database query identifier. + :vartype query_id: str + :ivar start_time: Observation start time. + :vartype start_time: ~datetime.datetime + :ivar end_time: Observation end time. + :vartype end_time: ~datetime.datetime + :ivar aggregation_function: Aggregation function name. + :vartype aggregation_function: str + :ivar database_names: The list of database names. + :vartype database_names: list[str] + :ivar query_execution_count: Number of query executions in this time interval. + :vartype query_execution_count: long + :ivar metric_name: Metric name. + :vartype metric_name: str + :ivar metric_display_name: Metric display name. + :vartype metric_display_name: str + :ivar metric_value: Metric value. + :vartype metric_value: float + :ivar metric_value_unit: Metric value unit. + :vartype metric_value_unit: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'query_id': {'key': 'properties.queryId', 'type': 'str'}, + 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, + 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, + 'aggregation_function': {'key': 'properties.aggregationFunction', 'type': 'str'}, + 'database_names': {'key': 'properties.databaseNames', 'type': '[str]'}, + 'query_execution_count': {'key': 'properties.queryExecutionCount', 'type': 'long'}, + 'metric_name': {'key': 'properties.metricName', 'type': 'str'}, + 'metric_display_name': {'key': 'properties.metricDisplayName', 'type': 'str'}, + 'metric_value': {'key': 'properties.metricValue', 'type': 'float'}, + 'metric_value_unit': {'key': 'properties.metricValueUnit', 'type': 'str'}, + } + + def __init__( + self, + *, + query_id: Optional[str] = None, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + aggregation_function: Optional[str] = None, + database_names: Optional[List[str]] = None, + query_execution_count: Optional[int] = None, + metric_name: Optional[str] = None, + metric_display_name: Optional[str] = None, + metric_value: Optional[float] = None, + metric_value_unit: Optional[str] = None, + **kwargs + ): + """ + :keyword query_id: Database query identifier. + :paramtype query_id: str + :keyword start_time: Observation start time. + :paramtype start_time: ~datetime.datetime + :keyword end_time: Observation end time. + :paramtype end_time: ~datetime.datetime + :keyword aggregation_function: Aggregation function name. + :paramtype aggregation_function: str + :keyword database_names: The list of database names. + :paramtype database_names: list[str] + :keyword query_execution_count: Number of query executions in this time interval. + :paramtype query_execution_count: long + :keyword metric_name: Metric name. + :paramtype metric_name: str + :keyword metric_display_name: Metric display name. + :paramtype metric_display_name: str + :keyword metric_value: Metric value. + :paramtype metric_value: float + :keyword metric_value_unit: Metric value unit. + :paramtype metric_value_unit: str + """ + super(QueryStatistic, self).__init__(**kwargs) + self.query_id = query_id + self.start_time = start_time + self.end_time = end_time + self.aggregation_function = aggregation_function + self.database_names = database_names + self.query_execution_count = query_execution_count + self.metric_name = metric_name + self.metric_display_name = metric_display_name + self.metric_value = metric_value + self.metric_value_unit = metric_value_unit + + +class QueryText(ProxyResource): + """Represents a Query Text. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar query_id: Query identifier unique to the server. + :vartype query_id: str + :ivar query_text: Query text. + :vartype query_text: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'query_id': {'key': 'properties.queryId', 'type': 'str'}, + 'query_text': {'key': 'properties.queryText', 'type': 'str'}, + } + + def __init__( + self, + *, + query_id: Optional[str] = None, + query_text: Optional[str] = None, + **kwargs + ): + """ + :keyword query_id: Query identifier unique to the server. + :paramtype query_id: str + :keyword query_text: Query text. + :paramtype query_text: str + """ + super(QueryText, self).__init__(**kwargs) + self.query_id = query_id + self.query_text = query_text + + +class QueryTextsResultList(msrest.serialization.Model): + """A list of query texts. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of query texts. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.QueryText] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[QueryText]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(QueryTextsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class RecommendationAction(ProxyResource): + """Represents a Recommendation Action. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar advisor_name: Advisor name. + :vartype advisor_name: str + :ivar session_id: Recommendation action session identifier. + :vartype session_id: str + :ivar action_id: Recommendation action identifier. + :vartype action_id: int + :ivar created_time: Recommendation action creation time. + :vartype created_time: ~datetime.datetime + :ivar expiration_time: Recommendation action expiration time. + :vartype expiration_time: ~datetime.datetime + :ivar reason: Recommendation action reason. + :vartype reason: str + :ivar recommendation_type: Recommendation action type. + :vartype recommendation_type: str + :ivar details: Recommendation action details. + :vartype details: dict[str, str] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'advisor_name': {'key': 'properties.advisorName', 'type': 'str'}, + 'session_id': {'key': 'properties.sessionId', 'type': 'str'}, + 'action_id': {'key': 'properties.actionId', 'type': 'int'}, + 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, + 'expiration_time': {'key': 'properties.expirationTime', 'type': 'iso-8601'}, + 'reason': {'key': 'properties.reason', 'type': 'str'}, + 'recommendation_type': {'key': 'properties.recommendationType', 'type': 'str'}, + 'details': {'key': 'properties.details', 'type': '{str}'}, + } + + def __init__( + self, + *, + advisor_name: Optional[str] = None, + session_id: Optional[str] = None, + action_id: Optional[int] = None, + created_time: Optional[datetime.datetime] = None, + expiration_time: Optional[datetime.datetime] = None, + reason: Optional[str] = None, + recommendation_type: Optional[str] = None, + details: Optional[Dict[str, str]] = None, + **kwargs + ): + """ + :keyword advisor_name: Advisor name. + :paramtype advisor_name: str + :keyword session_id: Recommendation action session identifier. + :paramtype session_id: str + :keyword action_id: Recommendation action identifier. + :paramtype action_id: int + :keyword created_time: Recommendation action creation time. + :paramtype created_time: ~datetime.datetime + :keyword expiration_time: Recommendation action expiration time. + :paramtype expiration_time: ~datetime.datetime + :keyword reason: Recommendation action reason. + :paramtype reason: str + :keyword recommendation_type: Recommendation action type. + :paramtype recommendation_type: str + :keyword details: Recommendation action details. + :paramtype details: dict[str, str] + """ + super(RecommendationAction, self).__init__(**kwargs) + self.advisor_name = advisor_name + self.session_id = session_id + self.action_id = action_id + self.created_time = created_time + self.expiration_time = expiration_time + self.reason = reason + self.recommendation_type = recommendation_type + self.details = details + + +class RecommendationActionsResultList(msrest.serialization.Model): + """A list of recommendation actions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of recommendation action advisors. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.RecommendationAction] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[RecommendationAction]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(RecommendationActionsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class RecommendedActionSessionsOperationStatus(msrest.serialization.Model): + """Recommendation action session operation status. + + :ivar name: Operation identifier. + :vartype name: str + :ivar start_time: Operation start time. + :vartype start_time: ~datetime.datetime + :ivar status: Operation status. + :vartype status: str + """ + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + start_time: Optional[datetime.datetime] = None, + status: Optional[str] = None, + **kwargs + ): + """ + :keyword name: Operation identifier. + :paramtype name: str + :keyword start_time: Operation start time. + :paramtype start_time: ~datetime.datetime + :keyword status: Operation status. + :paramtype status: str + """ + super(RecommendedActionSessionsOperationStatus, self).__init__(**kwargs) + self.name = name + self.start_time = start_time + self.status = status + + +class RecoverableServerResource(ProxyResource): + """A recoverable server resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar last_available_backup_date_time: The last available backup date time. + :vartype last_available_backup_date_time: str + :ivar service_level_objective: The service level objective. + :vartype service_level_objective: str + :ivar edition: Edition of the performance tier. + :vartype edition: str + :ivar v_core: vCore associated with the service level objective. + :vartype v_core: int + :ivar hardware_generation: Hardware generation associated with the service level objective. + :vartype hardware_generation: str + :ivar version: The MySQL version. + :vartype version: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'last_available_backup_date_time': {'readonly': True}, + 'service_level_objective': {'readonly': True}, + 'edition': {'readonly': True}, + 'v_core': {'readonly': True}, + 'hardware_generation': {'readonly': True}, + 'version': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'last_available_backup_date_time': {'key': 'properties.lastAvailableBackupDateTime', 'type': 'str'}, + 'service_level_objective': {'key': 'properties.serviceLevelObjective', 'type': 'str'}, + 'edition': {'key': 'properties.edition', 'type': 'str'}, + 'v_core': {'key': 'properties.vCore', 'type': 'int'}, + 'hardware_generation': {'key': 'properties.hardwareGeneration', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(RecoverableServerResource, self).__init__(**kwargs) + self.last_available_backup_date_time = None + self.service_level_objective = None + self.edition = None + self.v_core = None + self.hardware_generation = None + self.version = None + + +class ResourceIdentity(msrest.serialization.Model): + """Azure Active Directory identity configuration for a resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The Azure Active Directory principal id. + :vartype principal_id: str + :ivar type: The identity type. Set this to 'SystemAssigned' in order to automatically create + and assign an Azure Active Directory principal for the resource. Possible values include: + "SystemAssigned". + :vartype type: str or ~azure.mgmt.rdbms.mysql.models.IdentityType + :ivar tenant_id: The Azure Active Directory tenant id. + :vartype tenant_id: str + """ + + _validation = { + 'principal_id': {'readonly': True}, + 'tenant_id': {'readonly': True}, + } + + _attribute_map = { + 'principal_id': {'key': 'principalId', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tenant_id': {'key': 'tenantId', 'type': 'str'}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "IdentityType"]] = None, + **kwargs + ): + """ + :keyword type: The identity type. Set this to 'SystemAssigned' in order to automatically create + and assign an Azure Active Directory principal for the resource. Possible values include: + "SystemAssigned". + :paramtype type: str or ~azure.mgmt.rdbms.mysql.models.IdentityType + """ + super(ResourceIdentity, self).__init__(**kwargs) + self.principal_id = None + self.type = type + self.tenant_id = None + + +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar tags: A set of tags. Resource tags. + :vartype tags: dict[str, str] + :ivar location: Required. The geo-location where the resource lives. + :vartype location: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + **kwargs + ): + """ + :keyword tags: A set of tags. Resource tags. + :paramtype tags: dict[str, str] + :keyword location: Required. The geo-location where the resource lives. + :paramtype location: str + """ + super(TrackedResource, self).__init__(**kwargs) + self.tags = tags + self.location = location + + +class Server(TrackedResource): + """Represents a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar tags: A set of tags. Resource tags. + :vartype tags: dict[str, str] + :ivar location: Required. The geo-location where the resource lives. + :vartype location: str + :ivar identity: The Azure Active Directory identity of the server. + :vartype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity + :ivar sku: The SKU (pricing tier) of the server. + :vartype sku: ~azure.mgmt.rdbms.mysql.models.Sku + :ivar administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). + :vartype administrator_login: str + :ivar version: Server version. Possible values include: "5.6", "5.7", "8.0". + :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :ivar byok_enforcement: Status showing whether the server data encryption is enabled with + customer-managed keys. + :vartype byok_enforcement: str + :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :vartype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :ivar user_visible_state: A state of a server that is visible to user. Possible values include: + "Ready", "Dropping", "Disabled", "Inaccessible". + :vartype user_visible_state: str or ~azure.mgmt.rdbms.mysql.models.ServerState + :ivar fully_qualified_domain_name: The fully qualified domain name of a server. + :vartype fully_qualified_domain_name: str + :ivar earliest_restore_date: Earliest restore point creation time (ISO8601 format). + :vartype earliest_restore_date: ~datetime.datetime + :ivar storage_profile: Storage profile of a server. + :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :ivar replication_role: The replication role of the server. + :vartype replication_role: str + :ivar master_server_id: The master server id of a replica server. + :vartype master_server_id: str + :ivar replica_capacity: The maximum number of replicas that a master server can have. + :vartype replica_capacity: int + :ivar public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :ivar private_endpoint_connections: List of private endpoint connections on a server. + :vartype private_endpoint_connections: + list[~azure.mgmt.rdbms.mysql.models.ServerPrivateEndpointConnection] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + 'byok_enforcement': {'readonly': True}, + 'replica_capacity': {'minimum': 0}, + 'private_endpoint_connections': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'administrator_login': {'key': 'properties.administratorLogin', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, + 'byok_enforcement': {'key': 'properties.byokEnforcement', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'properties.infrastructureEncryption', 'type': 'str'}, + 'user_visible_state': {'key': 'properties.userVisibleState', 'type': 'str'}, + 'fully_qualified_domain_name': {'key': 'properties.fullyQualifiedDomainName', 'type': 'str'}, + 'earliest_restore_date': {'key': 'properties.earliestRestoreDate', 'type': 'iso-8601'}, + 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + 'master_server_id': {'key': 'properties.masterServerId', 'type': 'str'}, + 'replica_capacity': {'key': 'properties.replicaCapacity', 'type': 'int'}, + 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, + 'private_endpoint_connections': {'key': 'properties.privateEndpointConnections', 'type': '[ServerPrivateEndpointConnection]'}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + identity: Optional["ResourceIdentity"] = None, + sku: Optional["Sku"] = None, + administrator_login: Optional[str] = None, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + user_visible_state: Optional[Union[str, "ServerState"]] = None, + fully_qualified_domain_name: Optional[str] = None, + earliest_restore_date: Optional[datetime.datetime] = None, + storage_profile: Optional["StorageProfile"] = None, + replication_role: Optional[str] = None, + master_server_id: Optional[str] = None, + replica_capacity: Optional[int] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + **kwargs + ): + """ + :keyword tags: A set of tags. Resource tags. + :paramtype tags: dict[str, str] + :keyword location: Required. The geo-location where the resource lives. + :paramtype location: str + :keyword identity: The Azure Active Directory identity of the server. + :paramtype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity + :keyword sku: The SKU (pricing tier) of the server. + :paramtype sku: ~azure.mgmt.rdbms.mysql.models.Sku + :keyword administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). + :paramtype administrator_login: str + :keyword version: Server version. Possible values include: "5.6", "5.7", "8.0". + :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :paramtype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :keyword user_visible_state: A state of a server that is visible to user. Possible values + include: "Ready", "Dropping", "Disabled", "Inaccessible". + :paramtype user_visible_state: str or ~azure.mgmt.rdbms.mysql.models.ServerState + :keyword fully_qualified_domain_name: The fully qualified domain name of a server. + :paramtype fully_qualified_domain_name: str + :keyword earliest_restore_date: Earliest restore point creation time (ISO8601 format). + :paramtype earliest_restore_date: ~datetime.datetime + :keyword storage_profile: Storage profile of a server. + :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :keyword replication_role: The replication role of the server. + :paramtype replication_role: str + :keyword master_server_id: The master server id of a replica server. + :paramtype master_server_id: str + :keyword replica_capacity: The maximum number of replicas that a master server can have. + :paramtype replica_capacity: int + :keyword public_network_access: Whether or not public network access is allowed for this + server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values + include: "Enabled", "Disabled". + :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + """ + super(Server, self).__init__(tags=tags, location=location, **kwargs) + self.identity = identity + self.sku = sku + self.administrator_login = administrator_login + self.version = version + self.ssl_enforcement = ssl_enforcement + self.minimal_tls_version = minimal_tls_version + self.byok_enforcement = None + self.infrastructure_encryption = infrastructure_encryption + self.user_visible_state = user_visible_state + self.fully_qualified_domain_name = fully_qualified_domain_name + self.earliest_restore_date = earliest_restore_date + self.storage_profile = storage_profile + self.replication_role = replication_role + self.master_server_id = master_server_id + self.replica_capacity = replica_capacity + self.public_network_access = public_network_access + self.private_endpoint_connections = None + + +class ServerAdministratorResource(ProxyResource): + """Represents a and external administrator to be created. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar administrator_type: The type of administrator. The only acceptable values to pass in are + None and "ActiveDirectory". The default value is None. + :vartype administrator_type: str + :ivar login: The server administrator login account name. + :vartype login: str + :ivar sid: The server administrator Sid (Secure ID). + :vartype sid: str + :ivar tenant_id: The server Active Directory Administrator tenant id. + :vartype tenant_id: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'administrator_type': {'key': 'properties.administratorType', 'type': 'str'}, + 'login': {'key': 'properties.login', 'type': 'str'}, + 'sid': {'key': 'properties.sid', 'type': 'str'}, + 'tenant_id': {'key': 'properties.tenantId', 'type': 'str'}, + } + + def __init__( + self, + *, + administrator_type: Optional[str] = None, + login: Optional[str] = None, + sid: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs + ): + """ + :keyword administrator_type: The type of administrator. The only acceptable values to pass in + are None and "ActiveDirectory". The default value is None. + :paramtype administrator_type: str + :keyword login: The server administrator login account name. + :paramtype login: str + :keyword sid: The server administrator Sid (Secure ID). + :paramtype sid: str + :keyword tenant_id: The server Active Directory Administrator tenant id. + :paramtype tenant_id: str + """ + super(ServerAdministratorResource, self).__init__(**kwargs) + self.administrator_type = administrator_type + self.login = login + self.sid = sid + self.tenant_id = tenant_id + + +class ServerAdministratorResourceListResult(msrest.serialization.Model): + """The response to a list Active Directory Administrators request. + + :ivar value: The list of server Active Directory Administrators for the server. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerAdministratorResource]'}, + } + + def __init__( + self, + *, + value: Optional[List["ServerAdministratorResource"]] = None, + **kwargs + ): + """ + :keyword value: The list of server Active Directory Administrators for the server. + :paramtype value: list[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] + """ + super(ServerAdministratorResourceListResult, self).__init__(**kwargs) + self.value = value + + +class ServerForCreate(msrest.serialization.Model): + """Represents a server to be created. + + All required parameters must be populated in order to send to Azure. + + :ivar identity: The Azure Active Directory identity of the server. + :vartype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity + :ivar sku: The SKU (pricing tier) of the server. + :vartype sku: ~azure.mgmt.rdbms.mysql.models.Sku + :ivar properties: Required. Properties of the server. + :vartype properties: ~azure.mgmt.rdbms.mysql.models.ServerPropertiesForCreate + :ivar location: Required. The location the resource resides in. + :vartype location: str + :ivar tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :vartype tags: dict[str, str] + """ + + _validation = { + 'properties': {'required': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'properties': {'key': 'properties', 'type': 'ServerPropertiesForCreate'}, + 'location': {'key': 'location', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + } + + def __init__( + self, + *, + properties: "ServerPropertiesForCreate", + location: str, + identity: Optional["ResourceIdentity"] = None, + sku: Optional["Sku"] = None, + tags: Optional[Dict[str, str]] = None, + **kwargs + ): + """ + :keyword identity: The Azure Active Directory identity of the server. + :paramtype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity + :keyword sku: The SKU (pricing tier) of the server. + :paramtype sku: ~azure.mgmt.rdbms.mysql.models.Sku + :keyword properties: Required. Properties of the server. + :paramtype properties: ~azure.mgmt.rdbms.mysql.models.ServerPropertiesForCreate + :keyword location: Required. The location the resource resides in. + :paramtype location: str + :keyword tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :paramtype tags: dict[str, str] + """ + super(ServerForCreate, self).__init__(**kwargs) + self.identity = identity + self.sku = sku + self.properties = properties + self.location = location + self.tags = tags + + +class ServerKey(ProxyResource): + """A MySQL Server key. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar kind: Kind of encryption protector used to protect the key. + :vartype kind: str + :ivar server_key_type: The key type like 'AzureKeyVault'. Possible values include: + "AzureKeyVault". + :vartype server_key_type: str or ~azure.mgmt.rdbms.mysql.models.ServerKeyType + :ivar uri: The URI of the key. + :vartype uri: str + :ivar creation_date: The key creation date. + :vartype creation_date: ~datetime.datetime + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'kind': {'readonly': True}, + 'creation_date': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'kind': {'key': 'kind', 'type': 'str'}, + 'server_key_type': {'key': 'properties.serverKeyType', 'type': 'str'}, + 'uri': {'key': 'properties.uri', 'type': 'str'}, + 'creation_date': {'key': 'properties.creationDate', 'type': 'iso-8601'}, + } + + def __init__( + self, + *, + server_key_type: Optional[Union[str, "ServerKeyType"]] = None, + uri: Optional[str] = None, + **kwargs + ): + """ + :keyword server_key_type: The key type like 'AzureKeyVault'. Possible values include: + "AzureKeyVault". + :paramtype server_key_type: str or ~azure.mgmt.rdbms.mysql.models.ServerKeyType + :keyword uri: The URI of the key. + :paramtype uri: str + """ + super(ServerKey, self).__init__(**kwargs) + self.kind = None + self.server_key_type = server_key_type + self.uri = uri + self.creation_date = None + + +class ServerKeyListResult(msrest.serialization.Model): + """A list of MySQL Server keys. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: A list of MySQL Server keys. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.ServerKey] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerKey]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(ServerKeyListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ServerListResult(msrest.serialization.Model): + """A list of servers. + + :ivar value: The list of servers. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.Server] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Server]'}, + } + + def __init__( + self, + *, + value: Optional[List["Server"]] = None, + **kwargs + ): + """ + :keyword value: The list of servers. + :paramtype value: list[~azure.mgmt.rdbms.mysql.models.Server] + """ + super(ServerListResult, self).__init__(**kwargs) + self.value = value + + +class ServerPrivateEndpointConnection(msrest.serialization.Model): + """A private endpoint connection under a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id of the private endpoint connection. + :vartype id: str + :ivar properties: Private endpoint connection properties. + :vartype properties: ~azure.mgmt.rdbms.mysql.models.ServerPrivateEndpointConnectionProperties + """ + + _validation = { + 'id': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'ServerPrivateEndpointConnectionProperties'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(ServerPrivateEndpointConnection, self).__init__(**kwargs) + self.id = None + self.properties = None + + +class ServerPrivateEndpointConnectionProperties(msrest.serialization.Model): + """Properties of a private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar private_endpoint: Private endpoint which the connection belongs to. + :vartype private_endpoint: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointProperty + :ivar private_link_service_connection_state: Connection state of the private endpoint + connection. + :vartype private_link_service_connection_state: + ~azure.mgmt.rdbms.mysql.models.ServerPrivateLinkServiceConnectionStateProperty + :ivar provisioning_state: State of the private endpoint connection. Possible values include: + "Approving", "Ready", "Dropping", "Failed", "Rejecting". + :vartype provisioning_state: str or + ~azure.mgmt.rdbms.mysql.models.PrivateEndpointProvisioningState + """ + + _validation = { + 'provisioning_state': {'readonly': True}, + } + + _attribute_map = { + 'private_endpoint': {'key': 'privateEndpoint', 'type': 'PrivateEndpointProperty'}, + 'private_link_service_connection_state': {'key': 'privateLinkServiceConnectionState', 'type': 'ServerPrivateLinkServiceConnectionStateProperty'}, + 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, + } + + def __init__( + self, + *, + private_endpoint: Optional["PrivateEndpointProperty"] = None, + private_link_service_connection_state: Optional["ServerPrivateLinkServiceConnectionStateProperty"] = None, + **kwargs + ): + """ + :keyword private_endpoint: Private endpoint which the connection belongs to. + :paramtype private_endpoint: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointProperty + :keyword private_link_service_connection_state: Connection state of the private endpoint + connection. + :paramtype private_link_service_connection_state: + ~azure.mgmt.rdbms.mysql.models.ServerPrivateLinkServiceConnectionStateProperty + """ + super(ServerPrivateEndpointConnectionProperties, self).__init__(**kwargs) + self.private_endpoint = private_endpoint + self.private_link_service_connection_state = private_link_service_connection_state + self.provisioning_state = None + + +class ServerPrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): + """ServerPrivateLinkServiceConnectionStateProperty. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar status: Required. The private link service connection status. Possible values include: + "Approved", "Pending", "Rejected", "Disconnected". + :vartype status: str or ~azure.mgmt.rdbms.mysql.models.PrivateLinkServiceConnectionStateStatus + :ivar description: Required. The private link service connection description. + :vartype description: str + :ivar actions_required: The actions required for private link service connection. Possible + values include: "None". + :vartype actions_required: str or + ~azure.mgmt.rdbms.mysql.models.PrivateLinkServiceConnectionStateActionsRequire + """ + + _validation = { + 'status': {'required': True}, + 'description': {'required': True}, + 'actions_required': {'readonly': True}, + } + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + } + + def __init__( + self, + *, + status: Union[str, "PrivateLinkServiceConnectionStateStatus"], + description: str, + **kwargs + ): + """ + :keyword status: Required. The private link service connection status. Possible values include: + "Approved", "Pending", "Rejected", "Disconnected". + :paramtype status: str or + ~azure.mgmt.rdbms.mysql.models.PrivateLinkServiceConnectionStateStatus + :keyword description: Required. The private link service connection description. + :paramtype description: str + """ + super(ServerPrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + self.status = status + self.description = description + self.actions_required = None + + +class ServerPropertiesForCreate(msrest.serialization.Model): + """The properties used to create a new server. + + You probably want to use the sub-classes and not this class directly. Known + sub-classes are: ServerPropertiesForDefaultCreate, ServerPropertiesForGeoRestore, ServerPropertiesForRestore, ServerPropertiesForReplica. + + All required parameters must be populated in order to send to Azure. + + :ivar version: Server version. Possible values include: "5.6", "5.7", "8.0". + :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :vartype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :ivar public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :ivar storage_profile: Storage profile of a server. + :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :ivar create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :vartype create_mode: str or ~azure.mgmt.rdbms.mysql.models.CreateMode + """ + + _validation = { + 'create_mode': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + } + + _subtype_map = { + 'create_mode': {'Default': 'ServerPropertiesForDefaultCreate', 'GeoRestore': 'ServerPropertiesForGeoRestore', 'PointInTimeRestore': 'ServerPropertiesForRestore', 'Replica': 'ServerPropertiesForReplica'} + } + + def __init__( + self, + *, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + """ + :keyword version: Server version. Possible values include: "5.6", "5.7", "8.0". + :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :paramtype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :keyword public_network_access: Whether or not public network access is allowed for this + server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values + include: "Enabled", "Disabled". + :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :keyword storage_profile: Storage profile of a server. + :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + """ + super(ServerPropertiesForCreate, self).__init__(**kwargs) + self.version = version + self.ssl_enforcement = ssl_enforcement + self.minimal_tls_version = minimal_tls_version + self.infrastructure_encryption = infrastructure_encryption + self.public_network_access = public_network_access + self.storage_profile = storage_profile + self.create_mode = None # type: Optional[str] + + +class ServerPropertiesForDefaultCreate(ServerPropertiesForCreate): + """The properties used to create a new server. + + All required parameters must be populated in order to send to Azure. + + :ivar version: Server version. Possible values include: "5.6", "5.7", "8.0". + :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :vartype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :ivar public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :ivar storage_profile: Storage profile of a server. + :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :ivar create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :vartype create_mode: str or ~azure.mgmt.rdbms.mysql.models.CreateMode + :ivar administrator_login: Required. The administrator's login name of a server. Can only be + specified when the server is being created (and is required for creation). The login name is + required when updating password. + :vartype administrator_login: str + :ivar administrator_login_password: Required. The password of the administrator login. + :vartype administrator_login_password: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'administrator_login': {'required': True}, + 'administrator_login_password': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'administrator_login': {'key': 'administratorLogin', 'type': 'str'}, + 'administrator_login_password': {'key': 'administratorLoginPassword', 'type': 'str'}, + } + + def __init__( + self, + *, + administrator_login: str, + administrator_login_password: str, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + """ + :keyword version: Server version. Possible values include: "5.6", "5.7", "8.0". + :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :paramtype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :keyword public_network_access: Whether or not public network access is allowed for this + server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values + include: "Enabled", "Disabled". + :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :keyword storage_profile: Storage profile of a server. + :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :keyword administrator_login: Required. The administrator's login name of a server. Can only be + specified when the server is being created (and is required for creation). The login name is + required when updating password. + :paramtype administrator_login: str + :keyword administrator_login_password: Required. The password of the administrator login. + :paramtype administrator_login_password: str + """ + super(ServerPropertiesForDefaultCreate, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'Default' # type: str + self.administrator_login = administrator_login + self.administrator_login_password = administrator_login_password + + +class ServerPropertiesForGeoRestore(ServerPropertiesForCreate): + """The properties used to create a new server by restoring to a different region from a geo replicated backup. + + All required parameters must be populated in order to send to Azure. + + :ivar version: Server version. Possible values include: "5.6", "5.7", "8.0". + :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :vartype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :ivar public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :ivar storage_profile: Storage profile of a server. + :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :ivar create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :vartype create_mode: str or ~azure.mgmt.rdbms.mysql.models.CreateMode + :ivar source_server_id: Required. The source server id to restore from. + :vartype source_server_id: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + } + + def __init__( + self, + *, + source_server_id: str, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + """ + :keyword version: Server version. Possible values include: "5.6", "5.7", "8.0". + :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :paramtype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :keyword public_network_access: Whether or not public network access is allowed for this + server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values + include: "Enabled", "Disabled". + :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :keyword storage_profile: Storage profile of a server. + :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :keyword source_server_id: Required. The source server id to restore from. + :paramtype source_server_id: str + """ + super(ServerPropertiesForGeoRestore, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'GeoRestore' # type: str + self.source_server_id = source_server_id + + +class ServerPropertiesForReplica(ServerPropertiesForCreate): + """The properties to create a new replica. + + All required parameters must be populated in order to send to Azure. + + :ivar version: Server version. Possible values include: "5.6", "5.7", "8.0". + :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :vartype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :ivar public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :ivar storage_profile: Storage profile of a server. + :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :ivar create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :vartype create_mode: str or ~azure.mgmt.rdbms.mysql.models.CreateMode + :ivar source_server_id: Required. The master server id to create replica from. + :vartype source_server_id: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + } + + def __init__( + self, + *, + source_server_id: str, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + """ + :keyword version: Server version. Possible values include: "5.6", "5.7", "8.0". + :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :paramtype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :keyword public_network_access: Whether or not public network access is allowed for this + server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values + include: "Enabled", "Disabled". + :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :keyword storage_profile: Storage profile of a server. + :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :keyword source_server_id: Required. The master server id to create replica from. + :paramtype source_server_id: str + """ + super(ServerPropertiesForReplica, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'Replica' # type: str + self.source_server_id = source_server_id + + +class ServerPropertiesForRestore(ServerPropertiesForCreate): + """The properties used to create a new server by restoring from a backup. + + All required parameters must be populated in order to send to Azure. + + :ivar version: Server version. Possible values include: "5.6", "5.7", "8.0". + :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :vartype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :ivar public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :ivar storage_profile: Storage profile of a server. + :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :ivar create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :vartype create_mode: str or ~azure.mgmt.rdbms.mysql.models.CreateMode + :ivar source_server_id: Required. The source server id to restore from. + :vartype source_server_id: str + :ivar restore_point_in_time: Required. Restore point creation time (ISO8601 format), specifying + the time to restore from. + :vartype restore_point_in_time: ~datetime.datetime + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + 'restore_point_in_time': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + 'restore_point_in_time': {'key': 'restorePointInTime', 'type': 'iso-8601'}, + } + + def __init__( + self, + *, + source_server_id: str, + restore_point_in_time: datetime.datetime, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + """ + :keyword version: Server version. Possible values include: "5.6", "5.7", "8.0". + :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :paramtype infrastructure_encryption: str or + ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption + :keyword public_network_access: Whether or not public network access is allowed for this + server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values + include: "Enabled", "Disabled". + :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :keyword storage_profile: Storage profile of a server. + :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :keyword source_server_id: Required. The source server id to restore from. + :paramtype source_server_id: str + :keyword restore_point_in_time: Required. Restore point creation time (ISO8601 format), + specifying the time to restore from. + :paramtype restore_point_in_time: ~datetime.datetime + """ + super(ServerPropertiesForRestore, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'PointInTimeRestore' # type: str + self.source_server_id = source_server_id + self.restore_point_in_time = restore_point_in_time + + +class ServerSecurityAlertPolicy(ProxyResource): + """A server security alert policy. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar state: Specifies the state of the policy, whether it is enabled or disabled. Possible + values include: "Enabled", "Disabled". + :vartype state: str or ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicyState + :ivar disabled_alerts: Specifies an array of alerts that are disabled. Allowed values are: + Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly. + :vartype disabled_alerts: list[str] + :ivar email_addresses: Specifies an array of e-mail addresses to which the alert is sent. + :vartype email_addresses: list[str] + :ivar email_account_admins: Specifies that the alert is sent to the account administrators. + :vartype email_account_admins: bool + :ivar storage_endpoint: Specifies the blob storage endpoint (e.g. + https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection + audit logs. + :vartype storage_endpoint: str + :ivar storage_account_access_key: Specifies the identifier key of the Threat Detection audit + storage account. + :vartype storage_account_access_key: str + :ivar retention_days: Specifies the number of days to keep in the Threat Detection audit logs. + :vartype retention_days: int + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + 'disabled_alerts': {'key': 'properties.disabledAlerts', 'type': '[str]'}, + 'email_addresses': {'key': 'properties.emailAddresses', 'type': '[str]'}, + 'email_account_admins': {'key': 'properties.emailAccountAdmins', 'type': 'bool'}, + 'storage_endpoint': {'key': 'properties.storageEndpoint', 'type': 'str'}, + 'storage_account_access_key': {'key': 'properties.storageAccountAccessKey', 'type': 'str'}, + 'retention_days': {'key': 'properties.retentionDays', 'type': 'int'}, + } + + def __init__( + self, + *, + state: Optional[Union[str, "ServerSecurityAlertPolicyState"]] = None, + disabled_alerts: Optional[List[str]] = None, + email_addresses: Optional[List[str]] = None, + email_account_admins: Optional[bool] = None, + storage_endpoint: Optional[str] = None, + storage_account_access_key: Optional[str] = None, + retention_days: Optional[int] = None, + **kwargs + ): + """ + :keyword state: Specifies the state of the policy, whether it is enabled or disabled. Possible + values include: "Enabled", "Disabled". + :paramtype state: str or ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicyState + :keyword disabled_alerts: Specifies an array of alerts that are disabled. Allowed values are: + Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly. + :paramtype disabled_alerts: list[str] + :keyword email_addresses: Specifies an array of e-mail addresses to which the alert is sent. + :paramtype email_addresses: list[str] + :keyword email_account_admins: Specifies that the alert is sent to the account administrators. + :paramtype email_account_admins: bool + :keyword storage_endpoint: Specifies the blob storage endpoint (e.g. + https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection + audit logs. + :paramtype storage_endpoint: str + :keyword storage_account_access_key: Specifies the identifier key of the Threat Detection audit + storage account. + :paramtype storage_account_access_key: str + :keyword retention_days: Specifies the number of days to keep in the Threat Detection audit + logs. + :paramtype retention_days: int + """ + super(ServerSecurityAlertPolicy, self).__init__(**kwargs) + self.state = state + self.disabled_alerts = disabled_alerts + self.email_addresses = email_addresses + self.email_account_admins = email_account_admins + self.storage_endpoint = storage_endpoint + self.storage_account_access_key = storage_account_access_key + self.retention_days = retention_days + + +class ServerSecurityAlertPolicyListResult(msrest.serialization.Model): + """A list of the server's security alert policies. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerSecurityAlertPolicy]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(ServerSecurityAlertPolicyListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ServerUpdateParameters(msrest.serialization.Model): + """Parameters allowed to update for a server. + + :ivar identity: The Azure Active Directory identity of the server. + :vartype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity + :ivar sku: The SKU (pricing tier) of the server. + :vartype sku: ~azure.mgmt.rdbms.mysql.models.Sku + :ivar tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :vartype tags: dict[str, str] + :ivar storage_profile: Storage profile of a server. + :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :ivar administrator_login_password: The password of the administrator login. + :vartype administrator_login_password: str + :ivar version: The version of a server. Possible values include: "5.6", "5.7", "8.0". + :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :ivar public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :ivar replication_role: The replication role of the server. + :vartype replication_role: str + """ + + _attribute_map = { + 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, + 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + } + + def __init__( + self, + *, + identity: Optional["ResourceIdentity"] = None, + sku: Optional["Sku"] = None, + tags: Optional[Dict[str, str]] = None, + storage_profile: Optional["StorageProfile"] = None, + administrator_login_password: Optional[str] = None, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + replication_role: Optional[str] = None, + **kwargs + ): + """ + :keyword identity: The Azure Active Directory identity of the server. + :paramtype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity + :keyword sku: The SKU (pricing tier) of the server. + :paramtype sku: ~azure.mgmt.rdbms.mysql.models.Sku + :keyword tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :paramtype tags: dict[str, str] + :keyword storage_profile: Storage profile of a server. + :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile + :keyword administrator_login_password: The password of the administrator login. + :paramtype administrator_login_password: str + :keyword version: The version of a server. Possible values include: "5.6", "5.7", "8.0". + :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion + :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum + :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum + :keyword public_network_access: Whether or not public network access is allowed for this + server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values + include: "Enabled", "Disabled". + :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum + :keyword replication_role: The replication role of the server. + :paramtype replication_role: str + """ + super(ServerUpdateParameters, self).__init__(**kwargs) + self.identity = identity + self.sku = sku + self.tags = tags + self.storage_profile = storage_profile + self.administrator_login_password = administrator_login_password + self.version = version + self.ssl_enforcement = ssl_enforcement + self.minimal_tls_version = minimal_tls_version + self.public_network_access = public_network_access + self.replication_role = replication_role + + +class ServerUpgradeParameters(msrest.serialization.Model): + """ServerUpgradeParameters. + + :ivar target_server_version: Represents an server storage profile. + :vartype target_server_version: str + """ + + _attribute_map = { + 'target_server_version': {'key': 'properties.targetServerVersion', 'type': 'str'}, + } + + def __init__( + self, + *, + target_server_version: Optional[str] = None, + **kwargs + ): + """ + :keyword target_server_version: Represents an server storage profile. + :paramtype target_server_version: str + """ + super(ServerUpgradeParameters, self).__init__(**kwargs) + self.target_server_version = target_server_version + + +class Sku(msrest.serialization.Model): + """Billing information related properties of a server. + + All required parameters must be populated in order to send to Azure. + + :ivar name: Required. The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, + GP_Gen5_8. + :vartype name: str + :ivar tier: The tier of the particular SKU, e.g. Basic. Possible values include: "Basic", + "GeneralPurpose", "MemoryOptimized". + :vartype tier: str or ~azure.mgmt.rdbms.mysql.models.SkuTier + :ivar capacity: The scale up/out capacity, representing server's compute units. + :vartype capacity: int + :ivar size: The size code, to be interpreted by resource as appropriate. + :vartype size: str + :ivar family: The family of hardware. + :vartype family: str + """ + + _validation = { + 'name': {'required': True}, + 'capacity': {'minimum': 0}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'tier': {'key': 'tier', 'type': 'str'}, + 'capacity': {'key': 'capacity', 'type': 'int'}, + 'size': {'key': 'size', 'type': 'str'}, + 'family': {'key': 'family', 'type': 'str'}, + } + + def __init__( + self, + *, + name: str, + tier: Optional[Union[str, "SkuTier"]] = None, + capacity: Optional[int] = None, + size: Optional[str] = None, + family: Optional[str] = None, + **kwargs + ): + """ + :keyword name: Required. The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, + GP_Gen5_8. + :paramtype name: str + :keyword tier: The tier of the particular SKU, e.g. Basic. Possible values include: "Basic", + "GeneralPurpose", "MemoryOptimized". + :paramtype tier: str or ~azure.mgmt.rdbms.mysql.models.SkuTier + :keyword capacity: The scale up/out capacity, representing server's compute units. + :paramtype capacity: int + :keyword size: The size code, to be interpreted by resource as appropriate. + :paramtype size: str + :keyword family: The family of hardware. + :paramtype family: str + """ + super(Sku, self).__init__(**kwargs) + self.name = name + self.tier = tier + self.capacity = capacity + self.size = size + self.family = family + + +class StorageProfile(msrest.serialization.Model): + """Storage Profile properties of a server. + + :ivar backup_retention_days: Backup retention days for the server. + :vartype backup_retention_days: int + :ivar geo_redundant_backup: Enable Geo-redundant or not for server backup. Possible values + include: "Enabled", "Disabled". + :vartype geo_redundant_backup: str or ~azure.mgmt.rdbms.mysql.models.GeoRedundantBackup + :ivar storage_mb: Max storage allowed for a server. + :vartype storage_mb: int + :ivar storage_autogrow: Enable Storage Auto Grow. Possible values include: "Enabled", + "Disabled". + :vartype storage_autogrow: str or ~azure.mgmt.rdbms.mysql.models.StorageAutogrow + """ + + _attribute_map = { + 'backup_retention_days': {'key': 'backupRetentionDays', 'type': 'int'}, + 'geo_redundant_backup': {'key': 'geoRedundantBackup', 'type': 'str'}, + 'storage_mb': {'key': 'storageMB', 'type': 'int'}, + 'storage_autogrow': {'key': 'storageAutogrow', 'type': 'str'}, + } + + def __init__( + self, + *, + backup_retention_days: Optional[int] = None, + geo_redundant_backup: Optional[Union[str, "GeoRedundantBackup"]] = None, + storage_mb: Optional[int] = None, + storage_autogrow: Optional[Union[str, "StorageAutogrow"]] = None, + **kwargs + ): + """ + :keyword backup_retention_days: Backup retention days for the server. + :paramtype backup_retention_days: int + :keyword geo_redundant_backup: Enable Geo-redundant or not for server backup. Possible values + include: "Enabled", "Disabled". + :paramtype geo_redundant_backup: str or ~azure.mgmt.rdbms.mysql.models.GeoRedundantBackup + :keyword storage_mb: Max storage allowed for a server. + :paramtype storage_mb: int + :keyword storage_autogrow: Enable Storage Auto Grow. Possible values include: "Enabled", + "Disabled". + :paramtype storage_autogrow: str or ~azure.mgmt.rdbms.mysql.models.StorageAutogrow + """ + super(StorageProfile, self).__init__(**kwargs) + self.backup_retention_days = backup_retention_days + self.geo_redundant_backup = geo_redundant_backup + self.storage_mb = storage_mb + self.storage_autogrow = storage_autogrow + + +class TagsObject(msrest.serialization.Model): + """Tags object for patch operations. + + :ivar tags: A set of tags. Resource tags. + :vartype tags: dict[str, str] + """ + + _attribute_map = { + 'tags': {'key': 'tags', 'type': '{str}'}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + **kwargs + ): + """ + :keyword tags: A set of tags. Resource tags. + :paramtype tags: dict[str, str] + """ + super(TagsObject, self).__init__(**kwargs) + self.tags = tags + + +class TopQueryStatisticsInput(msrest.serialization.Model): + """Input to get top query statistics. + + All required parameters must be populated in order to send to Azure. + + :ivar number_of_top_queries: Required. Max number of top queries to return. + :vartype number_of_top_queries: int + :ivar aggregation_function: Required. Aggregation function name. + :vartype aggregation_function: str + :ivar observed_metric: Required. Observed metric name. + :vartype observed_metric: str + :ivar observation_start_time: Required. Observation start time. + :vartype observation_start_time: ~datetime.datetime + :ivar observation_end_time: Required. Observation end time. + :vartype observation_end_time: ~datetime.datetime + :ivar aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :vartype aggregation_window: str + """ + + _validation = { + 'number_of_top_queries': {'required': True}, + 'aggregation_function': {'required': True}, + 'observed_metric': {'required': True}, + 'observation_start_time': {'required': True}, + 'observation_end_time': {'required': True}, + 'aggregation_window': {'required': True}, + } + + _attribute_map = { + 'number_of_top_queries': {'key': 'properties.numberOfTopQueries', 'type': 'int'}, + 'aggregation_function': {'key': 'properties.aggregationFunction', 'type': 'str'}, + 'observed_metric': {'key': 'properties.observedMetric', 'type': 'str'}, + 'observation_start_time': {'key': 'properties.observationStartTime', 'type': 'iso-8601'}, + 'observation_end_time': {'key': 'properties.observationEndTime', 'type': 'iso-8601'}, + 'aggregation_window': {'key': 'properties.aggregationWindow', 'type': 'str'}, + } + + def __init__( + self, + *, + number_of_top_queries: int, + aggregation_function: str, + observed_metric: str, + observation_start_time: datetime.datetime, + observation_end_time: datetime.datetime, + aggregation_window: str, + **kwargs + ): + """ + :keyword number_of_top_queries: Required. Max number of top queries to return. + :paramtype number_of_top_queries: int + :keyword aggregation_function: Required. Aggregation function name. + :paramtype aggregation_function: str + :keyword observed_metric: Required. Observed metric name. + :paramtype observed_metric: str + :keyword observation_start_time: Required. Observation start time. + :paramtype observation_start_time: ~datetime.datetime + :keyword observation_end_time: Required. Observation end time. + :paramtype observation_end_time: ~datetime.datetime + :keyword aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :paramtype aggregation_window: str + """ + super(TopQueryStatisticsInput, self).__init__(**kwargs) + self.number_of_top_queries = number_of_top_queries + self.aggregation_function = aggregation_function + self.observed_metric = observed_metric + self.observation_start_time = observation_start_time + self.observation_end_time = observation_end_time + self.aggregation_window = aggregation_window + + +class TopQueryStatisticsResultList(msrest.serialization.Model): + """A list of query statistics. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of top query statistics. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.QueryStatistic] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[QueryStatistic]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(TopQueryStatisticsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class VirtualNetworkRule(ProxyResource): + """A virtual network rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar virtual_network_subnet_id: The ARM resource id of the virtual network subnet. + :vartype virtual_network_subnet_id: str + :ivar ignore_missing_vnet_service_endpoint: Create firewall rule before the virtual network has + vnet service endpoint enabled. + :vartype ignore_missing_vnet_service_endpoint: bool + :ivar state: Virtual Network Rule State. Possible values include: "Initializing", "InProgress", + "Ready", "Deleting", "Unknown". + :vartype state: str or ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRuleState + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'state': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'virtual_network_subnet_id': {'key': 'properties.virtualNetworkSubnetId', 'type': 'str'}, + 'ignore_missing_vnet_service_endpoint': {'key': 'properties.ignoreMissingVnetServiceEndpoint', 'type': 'bool'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + } + + def __init__( + self, + *, + virtual_network_subnet_id: Optional[str] = None, + ignore_missing_vnet_service_endpoint: Optional[bool] = None, + **kwargs + ): + """ + :keyword virtual_network_subnet_id: The ARM resource id of the virtual network subnet. + :paramtype virtual_network_subnet_id: str + :keyword ignore_missing_vnet_service_endpoint: Create firewall rule before the virtual network + has vnet service endpoint enabled. + :paramtype ignore_missing_vnet_service_endpoint: bool + """ + super(VirtualNetworkRule, self).__init__(**kwargs) + self.virtual_network_subnet_id = virtual_network_subnet_id + self.ignore_missing_vnet_service_endpoint = ignore_missing_vnet_service_endpoint + self.state = None + + +class VirtualNetworkRuleListResult(msrest.serialization.Model): + """A list of virtual network rules. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[VirtualNetworkRule]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(VirtualNetworkRuleListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class WaitStatistic(ProxyResource): + """Represents a Wait Statistic. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar start_time: Observation start time. + :vartype start_time: ~datetime.datetime + :ivar end_time: Observation end time. + :vartype end_time: ~datetime.datetime + :ivar event_name: Wait event name. + :vartype event_name: str + :ivar event_type_name: Wait event type name. + :vartype event_type_name: str + :ivar query_id: Database query identifier. + :vartype query_id: long + :ivar database_name: Database Name. + :vartype database_name: str + :ivar user_id: Database user identifier. + :vartype user_id: long + :ivar count: Wait event count observed in this time interval. + :vartype count: long + :ivar total_time_in_ms: Total time of wait in milliseconds in this time interval. + :vartype total_time_in_ms: float + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, + 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, + 'event_name': {'key': 'properties.eventName', 'type': 'str'}, + 'event_type_name': {'key': 'properties.eventTypeName', 'type': 'str'}, + 'query_id': {'key': 'properties.queryId', 'type': 'long'}, + 'database_name': {'key': 'properties.databaseName', 'type': 'str'}, + 'user_id': {'key': 'properties.userId', 'type': 'long'}, + 'count': {'key': 'properties.count', 'type': 'long'}, + 'total_time_in_ms': {'key': 'properties.totalTimeInMs', 'type': 'float'}, + } + + def __init__( + self, + *, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + event_name: Optional[str] = None, + event_type_name: Optional[str] = None, + query_id: Optional[int] = None, + database_name: Optional[str] = None, + user_id: Optional[int] = None, + count: Optional[int] = None, + total_time_in_ms: Optional[float] = None, + **kwargs + ): + """ + :keyword start_time: Observation start time. + :paramtype start_time: ~datetime.datetime + :keyword end_time: Observation end time. + :paramtype end_time: ~datetime.datetime + :keyword event_name: Wait event name. + :paramtype event_name: str + :keyword event_type_name: Wait event type name. + :paramtype event_type_name: str + :keyword query_id: Database query identifier. + :paramtype query_id: long + :keyword database_name: Database Name. + :paramtype database_name: str + :keyword user_id: Database user identifier. + :paramtype user_id: long + :keyword count: Wait event count observed in this time interval. + :paramtype count: long + :keyword total_time_in_ms: Total time of wait in milliseconds in this time interval. + :paramtype total_time_in_ms: float + """ + super(WaitStatistic, self).__init__(**kwargs) + self.start_time = start_time + self.end_time = end_time + self.event_name = event_name + self.event_type_name = event_type_name + self.query_id = query_id + self.database_name = database_name + self.user_id = user_id + self.count = count + self.total_time_in_ms = total_time_in_ms + + +class WaitStatisticsInput(msrest.serialization.Model): + """Input to get wait statistics. + + All required parameters must be populated in order to send to Azure. + + :ivar observation_start_time: Required. Observation start time. + :vartype observation_start_time: ~datetime.datetime + :ivar observation_end_time: Required. Observation end time. + :vartype observation_end_time: ~datetime.datetime + :ivar aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :vartype aggregation_window: str + """ + + _validation = { + 'observation_start_time': {'required': True}, + 'observation_end_time': {'required': True}, + 'aggregation_window': {'required': True}, + } + + _attribute_map = { + 'observation_start_time': {'key': 'properties.observationStartTime', 'type': 'iso-8601'}, + 'observation_end_time': {'key': 'properties.observationEndTime', 'type': 'iso-8601'}, + 'aggregation_window': {'key': 'properties.aggregationWindow', 'type': 'str'}, + } + + def __init__( + self, + *, + observation_start_time: datetime.datetime, + observation_end_time: datetime.datetime, + aggregation_window: str, + **kwargs + ): + """ + :keyword observation_start_time: Required. Observation start time. + :paramtype observation_start_time: ~datetime.datetime + :keyword observation_end_time: Required. Observation end time. + :paramtype observation_end_time: ~datetime.datetime + :keyword aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :paramtype aggregation_window: str + """ + super(WaitStatisticsInput, self).__init__(**kwargs) + self.observation_start_time = observation_start_time + self.observation_end_time = observation_end_time + self.aggregation_window = aggregation_window + + +class WaitStatisticsResultList(msrest.serialization.Model): + """A list of wait statistics. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of wait statistics. + :vartype value: list[~azure.mgmt.rdbms.mysql.models.WaitStatistic] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[WaitStatistic]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(WaitStatisticsResultList, self).__init__(**kwargs) + self.value = None + self.next_link = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/models/_my_sql_management_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/models/_my_sql_management_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..723b9304de8d43422b71801c861d9edf4b6199f3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/models/_my_sql_management_client_enums.py @@ -0,0 +1,169 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from six import with_metaclass +from azure.core import CaseInsensitiveEnumMeta + + +class CreateMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The mode to create a new server. + """ + + DEFAULT = "Default" + POINT_IN_TIME_RESTORE = "PointInTimeRestore" + GEO_RESTORE = "GeoRestore" + REPLICA = "Replica" + +class GeoRedundantBackup(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Enable Geo-redundant or not for server backup. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class IdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an + Azure Active Directory principal for the resource. + """ + + SYSTEM_ASSIGNED = "SystemAssigned" + +class InfrastructureEncryption(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Add a second layer of encryption for your data using new encryption algorithm which gives + additional data protection. Value is optional but if passed in, must be 'Disabled' or + 'Enabled'. + """ + + #: Default value for single layer of encryption for data at rest. + ENABLED = "Enabled" + #: Additional (2nd) layer of encryption for data at rest. + DISABLED = "Disabled" + +class MinimalTlsVersionEnum(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Enforce a minimal Tls version for the server. + """ + + TLS1_0 = "TLS1_0" + TLS1_1 = "TLS1_1" + TLS1_2 = "TLS1_2" + TLS_ENFORCEMENT_DISABLED = "TLSEnforcementDisabled" + +class OperationOrigin(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The intended executor of the operation. + """ + + NOT_SPECIFIED = "NotSpecified" + USER = "user" + SYSTEM = "system" + +class PrivateEndpointProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """State of the private endpoint connection. + """ + + APPROVING = "Approving" + READY = "Ready" + DROPPING = "Dropping" + FAILED = "Failed" + REJECTING = "Rejecting" + +class PrivateLinkServiceConnectionStateActionsRequire(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The actions required for private link service connection. + """ + + NONE = "None" + +class PrivateLinkServiceConnectionStateStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The private link service connection status. + """ + + APPROVED = "Approved" + PENDING = "Pending" + REJECTED = "Rejected" + DISCONNECTED = "Disconnected" + +class PublicNetworkAccessEnum(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Whether or not public network access is allowed for this server. Value is optional but if + passed in, must be 'Enabled' or 'Disabled' + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class QueryPerformanceInsightResetDataResultState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Indicates result of the operation. + """ + + SUCCEEDED = "Succeeded" + FAILED = "Failed" + +class SecurityAlertPolicyName(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + + DEFAULT = "Default" + +class ServerKeyType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The key type like 'AzureKeyVault'. + """ + + AZURE_KEY_VAULT = "AzureKeyVault" + +class ServerSecurityAlertPolicyState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Specifies the state of the policy, whether it is enabled or disabled. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class ServerState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """A state of a server that is visible to user. + """ + + READY = "Ready" + DROPPING = "Dropping" + DISABLED = "Disabled" + INACCESSIBLE = "Inaccessible" + +class ServerVersion(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The version of a server. + """ + + FIVE6 = "5.6" + FIVE7 = "5.7" + EIGHT0 = "8.0" + +class SkuTier(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The tier of the particular SKU, e.g. Basic. + """ + + BASIC = "Basic" + GENERAL_PURPOSE = "GeneralPurpose" + MEMORY_OPTIMIZED = "MemoryOptimized" + +class SslEnforcementEnum(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Enable ssl enforcement or not when connect to server. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class StorageAutogrow(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Enable Storage Auto Grow. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class VirtualNetworkRuleState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Virtual Network Rule State + """ + + INITIALIZING = "Initializing" + IN_PROGRESS = "InProgress" + READY = "Ready" + DELETING = "Deleting" + UNKNOWN = "Unknown" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c44d71d2baae3cc96a517fc8200c0a84cd9f350 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/__init__.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._servers_operations import ServersOperations +from ._replicas_operations import ReplicasOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._virtual_network_rules_operations import VirtualNetworkRulesOperations +from ._databases_operations import DatabasesOperations +from ._configurations_operations import ConfigurationsOperations +from ._server_parameters_operations import ServerParametersOperations +from ._log_files_operations import LogFilesOperations +from ._server_administrators_operations import ServerAdministratorsOperations +from ._recoverable_servers_operations import RecoverableServersOperations +from ._server_based_performance_tier_operations import ServerBasedPerformanceTierOperations +from ._location_based_performance_tier_operations import LocationBasedPerformanceTierOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._operations import Operations +from ._server_security_alert_policies_operations import ServerSecurityAlertPoliciesOperations +from ._query_texts_operations import QueryTextsOperations +from ._top_query_statistics_operations import TopQueryStatisticsOperations +from ._wait_statistics_operations import WaitStatisticsOperations +from ._my_sql_management_client_operations import MySQLManagementClientOperationsMixin +from ._advisors_operations import AdvisorsOperations +from ._recommended_actions_operations import RecommendedActionsOperations +from ._location_based_recommended_action_sessions_operation_status_operations import LocationBasedRecommendedActionSessionsOperationStatusOperations +from ._location_based_recommended_action_sessions_result_operations import LocationBasedRecommendedActionSessionsResultOperations +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._private_link_resources_operations import PrivateLinkResourcesOperations +from ._server_keys_operations import ServerKeysOperations + +__all__ = [ + 'ServersOperations', + 'ReplicasOperations', + 'FirewallRulesOperations', + 'VirtualNetworkRulesOperations', + 'DatabasesOperations', + 'ConfigurationsOperations', + 'ServerParametersOperations', + 'LogFilesOperations', + 'ServerAdministratorsOperations', + 'RecoverableServersOperations', + 'ServerBasedPerformanceTierOperations', + 'LocationBasedPerformanceTierOperations', + 'CheckNameAvailabilityOperations', + 'Operations', + 'ServerSecurityAlertPoliciesOperations', + 'QueryTextsOperations', + 'TopQueryStatisticsOperations', + 'WaitStatisticsOperations', + 'MySQLManagementClientOperationsMixin', + 'AdvisorsOperations', + 'RecommendedActionsOperations', + 'LocationBasedRecommendedActionSessionsOperationStatusOperations', + 'LocationBasedRecommendedActionSessionsResultOperations', + 'PrivateEndpointConnectionsOperations', + 'PrivateLinkResourcesOperations', + 'ServerKeysOperations', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_advisors_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_advisors_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..12c878e5694ebb4cf2bfe888a16f0fef52e10bbc --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_advisors_operations.py @@ -0,0 +1,248 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + advisor_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "advisorName": _SERIALIZER.url("advisor_name", advisor_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class AdvisorsOperations(object): + """AdvisorsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + **kwargs: Any + ) -> "_models.Advisor": + """Get a recommendation action advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Advisor, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.Advisor + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Advisor"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Advisor', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.AdvisorsResultList"]: + """List recommendation action advisors. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either AdvisorsResultList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.AdvisorsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.AdvisorsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AdvisorsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_check_name_availability_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_check_name_availability_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..ec285ffc02ad0e8cec0ee6597c775d56d44691ff --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_check_name_availability_operations.py @@ -0,0 +1,140 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_execute_request( + subscription_id: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + +class CheckNameAvailabilityOperations(object): + """CheckNameAvailabilityOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def execute( + self, + name_availability_request: "_models.NameAvailabilityRequest", + **kwargs: Any + ) -> "_models.NameAvailability": + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. + :type name_availability_request: ~azure.mgmt.rdbms.mysql.models.NameAvailabilityRequest + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.NameAvailability + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + + request = build_execute_request( + subscription_id=self._config.subscription_id, + content_type=content_type, + json=_json, + template_url=self.execute.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('NameAvailability', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_configurations_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_configurations_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..99a7fc4ac3e5ff69a99fdd724ed9a2e062d27884 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_configurations_operations.py @@ -0,0 +1,422 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_create_or_update_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + configuration_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "configurationName": _SERIALIZER.url("configuration_name", configuration_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + configuration_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "configurationName": _SERIALIZER.url("configuration_name", configuration_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class ConfigurationsOperations(object): + """ConfigurationsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> Optional["_models.Configuration"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'Configuration') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> LROPoller["_models.Configuration"]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.mysql.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Configuration or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Configuration] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Configuration', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + **kwargs: Any + ) -> "_models.Configuration": + """Gets information about a configuration of server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Configuration, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.Configuration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.ConfigurationListResult"]: + """List all the configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConfigurationListResult or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_databases_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_databases_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..f8e305c0956c7882e9d522cdb6dca1c2f73bd22d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_databases_operations.py @@ -0,0 +1,562 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_create_or_update_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + database_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_delete_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="DELETE", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class DatabasesOperations(object): + """DatabasesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> Optional["_models.Database"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Database"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'Database') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Database', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> LROPoller["_models.Database"]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. + :type parameters: ~azure.mgmt.rdbms.mysql.models.Database + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Database or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Database] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Database', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace + def begin_delete( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> "_models.Database": + """Gets information about a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Database, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.Database + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.DatabaseListResult"]: + """List all the databases in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DatabaseListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.DatabaseListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.DatabaseListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DatabaseListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_firewall_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_firewall_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..f3fee404c123e6bae9f0c7b8bd5bee69bc3f9503 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_firewall_rules_operations.py @@ -0,0 +1,564 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_create_or_update_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_delete_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="DELETE", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class FirewallRulesOperations(object): + """FirewallRulesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> Optional["_models.FirewallRule"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FirewallRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'FirewallRule') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> LROPoller["_models.FirewallRule"]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. + :type parameters: ~azure.mgmt.rdbms.mysql.models.FirewallRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.FirewallRule] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('FirewallRule', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace + def begin_delete( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> "_models.FirewallRule": + """Gets information about a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FirewallRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.FirewallRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.FirewallRuleListResult"]: + """List all the firewall rules in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FirewallRuleListResult or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.FirewallRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("FirewallRuleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_location_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_location_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..7751714c3fe9a93d2f4b3cded3dfceee2c0dafd5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_location_based_performance_tier_operations.py @@ -0,0 +1,150 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_request( + subscription_id: str, + location_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/performanceTiers') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class LocationBasedPerformanceTierOperations(object): + """LocationBasedPerformanceTierOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + location_name: str, + **kwargs: Any + ) -> Iterable["_models.PerformanceTierListResult"]: + """List all the performance tiers at specified location in a given subscription. + + :param location_name: The name of the location. + :type location_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PerformanceTierListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_operation_status_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_operation_status_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..fd7182f6cc4299fa32be114aa2519a8ac4805c26 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_operation_status_operations.py @@ -0,0 +1,133 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + subscription_id: str, + location_name: str, + operation_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsAzureAsyncOperation/{operationId}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, 'str'), + "operationId": _SERIALIZER.url("operation_id", operation_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class LocationBasedRecommendedActionSessionsOperationStatusOperations(object): + """LocationBasedRecommendedActionSessionsOperationStatusOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + location_name: str, + operation_id: str, + **kwargs: Any + ) -> "_models.RecommendedActionSessionsOperationStatus": + """Recommendation action session operation status. + + :param location_name: The name of the location. + :type location_name: str + :param operation_id: The operation identifier. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecommendedActionSessionsOperationStatus, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.RecommendedActionSessionsOperationStatus + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendedActionSessionsOperationStatus"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + operation_id=operation_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecommendedActionSessionsOperationStatus', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsAzureAsyncOperation/{operationId}'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_result_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_result_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..95994c1e61fa56b7250b9ea81a2d49e945d4a377 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_result_operations.py @@ -0,0 +1,158 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_request( + subscription_id: str, + location_name: str, + operation_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsOperationResults/{operationId}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, 'str'), + "operationId": _SERIALIZER.url("operation_id", operation_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class LocationBasedRecommendedActionSessionsResultOperations(object): + """LocationBasedRecommendedActionSessionsResultOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + location_name: str, + operation_id: str, + **kwargs: Any + ) -> Iterable["_models.RecommendationActionsResultList"]: + """Recommendation action session operation result. + + :param location_name: The name of the location. + :type location_name: str + :param operation_id: The operation identifier. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RecommendationActionsResultList or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationActionsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationActionsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + operation_id=operation_id, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + operation_id=operation_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RecommendationActionsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsOperationResults/{operationId}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_log_files_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_log_files_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..cadebf2046a3af49496a388e174921f33b88085f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_log_files_operations.py @@ -0,0 +1,156 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/logFiles') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class LogFilesOperations(object): + """LogFilesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.LogFileListResult"]: + """List all the log files in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either LogFileListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.LogFileListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.LogFileListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("LogFileListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/logFiles'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_my_sql_management_client_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_my_sql_management_client_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..82f78d4e9137dc81fc63ae990318c529a8e5777d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_my_sql_management_client_operations.py @@ -0,0 +1,257 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_reset_query_performance_insight_data_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/resetQueryPerformanceInsightData') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_create_recommended_action_session_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + advisor_name: str, + *, + database_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "advisorName": _SERIALIZER.url("advisor_name", advisor_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + query_parameters['databaseName'] = _SERIALIZER.query("database_name", database_name, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + **kwargs + ) + +class MySQLManagementClientOperationsMixin(object): + + @distributed_trace + def reset_query_performance_insight_data( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.QueryPerformanceInsightResetDataResult": + """Reset data for Query Performance Insight. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryPerformanceInsightResetDataResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.QueryPerformanceInsightResetDataResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryPerformanceInsightResetDataResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_reset_query_performance_insight_data_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.reset_query_performance_insight_data.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryPerformanceInsightResetDataResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + reset_query_performance_insight_data.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/resetQueryPerformanceInsightData'} # type: ignore + + + def _create_recommended_action_session_initial( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + database_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_create_recommended_action_session_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + database_name=database_name, + template_url=self._create_recommended_action_session_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _create_recommended_action_session_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession'} # type: ignore + + + @distributed_trace + def begin_create_recommended_action_session( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + database_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Create recommendation action session for the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_recommended_action_session_initial( + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_recommended_action_session.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..7b5e2700b5fac4d920ca88f2f206c9525e5a3610 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_operations.py @@ -0,0 +1,114 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_request( + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/providers/Microsoft.DBforMySQL/operations') + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class Operations(object): + """Operations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + **kwargs: Any + ) -> "_models.OperationListResult": + """Lists all of the available REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationListResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.OperationListResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_list_request( + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list.metadata = {'url': '/providers/Microsoft.DBforMySQL/operations'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_private_endpoint_connections_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_private_endpoint_connections_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..e5f46fd4b2e8f8d404d4ca346e8a2b4ec7e0979f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_private_endpoint_connections_operations.py @@ -0,0 +1,733 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_create_or_update_request_initial( + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + subscription_id: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_delete_request_initial( + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="DELETE", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_update_tags_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PATCH", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_list_by_server_request( + resource_group_name: str, + server_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class PrivateEndpointConnectionsOperations(object): + """PrivateEndpointConnectionsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> "_models.PrivateEndpointConnection": + """Gets a private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + + def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.PrivateEndpointConnection", + **kwargs: Any + ) -> Optional["_models.PrivateEndpointConnection"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.PrivateEndpointConnection"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'PrivateEndpointConnection') + + request = build_create_or_update_request_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.PrivateEndpointConnection", + **kwargs: Any + ) -> LROPoller["_models.PrivateEndpointConnection"]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: + :type parameters: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + + @distributed_trace + def begin_delete( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def _update_tags_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.TagsObject", + **kwargs: Any + ) -> "_models.PrivateEndpointConnection": + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'TagsObject') + + request = build_update_tags_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + content_type=content_type, + json=_json, + template_url=self._update_tags_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _update_tags_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + + @distributed_trace + def begin_update_tags( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.TagsObject", + **kwargs: Any + ) -> LROPoller["_models.PrivateEndpointConnection"]: + """Updates tags on private endpoint connection. + + Updates private endpoint connection with the specified tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: Parameters supplied to the Update private endpoint connection Tags + operation. + :type parameters: ~azure.mgmt.rdbms.mysql.models.TagsObject + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._update_tags_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.PrivateEndpointConnectionListResult"]: + """Gets all private endpoint connections on a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateEndpointConnectionListResult or the result + of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnectionListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_private_link_resources_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_private_link_resources_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c97062993a96ca36e9d03088b5c14e30a91afb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_private_link_resources_operations.py @@ -0,0 +1,250 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_by_server_request( + resource_group_name: str, + server_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_get_request( + resource_group_name: str, + server_name: str, + group_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources/{groupName}') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "groupName": _SERIALIZER.url("group_name", group_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class PrivateLinkResourcesOperations(object): + """PrivateLinkResourcesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.PrivateLinkResourceListResult"]: + """Gets the private link resources for MySQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateLinkResourceListResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateLinkResourceListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources'} # type: ignore + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + group_name: str, + **kwargs: Any + ) -> "_models.PrivateLinkResource": + """Gets a private link resource for MySQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param group_name: The name of the private link resource. + :type group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateLinkResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.PrivateLinkResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + group_name=group_name, + subscription_id=self._config.subscription_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateLinkResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources/{groupName}'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_query_texts_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_query_texts_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..96e88030c40f1400010bb52c40e7ca08be10e59f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_query_texts_operations.py @@ -0,0 +1,257 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, List, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + query_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts/{queryId}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "queryId": _SERIALIZER.url("query_id", query_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + query_ids: List[str], + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + query_parameters['queryIds'] = [_SERIALIZER.query("query_ids", q, 'str') if q is not None else '' for q in query_ids] + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class QueryTextsOperations(object): + """QueryTextsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + query_id: str, + **kwargs: Any + ) -> "_models.QueryText": + """Retrieve the Query-Store query texts for the queryId. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_id: The Query-Store query identifier. + :type query_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryText, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.QueryText + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryText"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + query_id=query_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryText', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts/{queryId}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + query_ids: List[str], + **kwargs: Any + ) -> Iterable["_models.QueryTextsResultList"]: + """Retrieve the Query-Store query texts for specified queryIds. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_ids: The query identifiers. + :type query_ids: list[str] + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either QueryTextsResultList or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.QueryTextsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryTextsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + query_ids=query_ids, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + query_ids=query_ids, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("QueryTextsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_recommended_actions_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_recommended_actions_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..a6906740ddb8b812c815b21d569bf8480721cee3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_recommended_actions_operations.py @@ -0,0 +1,272 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + advisor_name: str, + recommended_action_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "advisorName": _SERIALIZER.url("advisor_name", advisor_name, 'str'), + "recommendedActionName": _SERIALIZER.url("recommended_action_name", recommended_action_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + advisor_name: str, + *, + session_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "advisorName": _SERIALIZER.url("advisor_name", advisor_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + if session_id is not None: + query_parameters['sessionId'] = _SERIALIZER.query("session_id", session_id, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class RecommendedActionsOperations(object): + """RecommendedActionsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + recommended_action_name: str, + **kwargs: Any + ) -> "_models.RecommendationAction": + """Retrieve recommended actions from the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param recommended_action_name: The recommended action name. + :type recommended_action_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecommendationAction, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.RecommendationAction + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationAction"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + recommended_action_name=recommended_action_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecommendationAction', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + advisor_name: str, + session_id: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.RecommendationActionsResultList"]: + """Retrieve recommended actions from the advisor. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param advisor_name: The advisor name for recommendation action. + :type advisor_name: str + :param session_id: The recommendation action session identifier. + :type session_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RecommendationActionsResultList or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationActionsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecommendationActionsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + session_id=session_id, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + advisor_name=advisor_name, + session_id=session_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RecommendationActionsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_recoverable_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_recoverable_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..8fae4d01009164b659f0abca3a66ee9f5d34d930 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_recoverable_servers_operations.py @@ -0,0 +1,133 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/recoverableServers') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class RecoverableServersOperations(object): + """RecoverableServersOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.RecoverableServerResource": + """Gets a recoverable MySQL Server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecoverableServerResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.RecoverableServerResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecoverableServerResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecoverableServerResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/recoverableServers'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_replicas_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_replicas_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..9dd03ba5d24f609c1f1e4e457a7ec41118324ab4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_replicas_operations.py @@ -0,0 +1,156 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/replicas') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class ReplicasOperations(object): + """ReplicasOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.ServerListResult"]: + """List all the replicas for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/replicas'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_administrators_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_administrators_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..5c6bf863ceb056b2ef922d6affb456534fe5b9e6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_administrators_operations.py @@ -0,0 +1,545 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_create_or_update_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_delete_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="DELETE", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class ServerAdministratorsOperations(object): + """ServerAdministratorsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.ServerAdministratorResource": + """Gets information about a AAD server administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerAdministratorResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + + def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + properties: "_models.ServerAdministratorResource", + **kwargs: Any + ) -> "_models.ServerAdministratorResource": + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(properties, 'ServerAdministratorResource') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + properties: "_models.ServerAdministratorResource", + **kwargs: Any + ) -> LROPoller["_models.ServerAdministratorResource"]: + """Creates or update active directory administrator on an existing server. The update action will + overwrite the existing administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param properties: The required parameters for creating or updating an AAD server + administrator. + :type properties: ~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ServerAdministratorResource or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + properties=properties, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + def _delete_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + + @distributed_trace + def begin_delete( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes server active directory administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + @distributed_trace + def list( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.ServerAdministratorResourceListResult"]: + """Returns a list of server Administrators. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerAdministratorResourceListResult or the + result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResourceListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResourceListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ServerAdministratorResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..0267492c61d64f5115cb85c743eea7a032ae98fb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_based_performance_tier_operations.py @@ -0,0 +1,157 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/performanceTiers') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class ServerBasedPerformanceTierOperations(object): + """ServerBasedPerformanceTierOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.PerformanceTierListResult"]: + """List all the performance tiers for a MySQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PerformanceTierListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_keys_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_keys_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d08a5c90b12a4bc261ad2af1387edfbdda0a3d2a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_keys_operations.py @@ -0,0 +1,561 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_get_request( + resource_group_name: str, + server_name: str, + key_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "keyName": _SERIALIZER.url("key_name", key_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_create_or_update_request_initial( + server_name: str, + key_name: str, + subscription_id: str, + resource_group_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}') + path_format_arguments = { + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "keyName": _SERIALIZER.url("key_name", key_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_delete_request_initial( + server_name: str, + key_name: str, + subscription_id: str, + resource_group_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}') + path_format_arguments = { + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "keyName": _SERIALIZER.url("key_name", key_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="DELETE", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class ServerKeysOperations(object): + """ServerKeysOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.ServerKeyListResult"]: + """Gets a list of Server keys. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerKeyListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerKeyListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKeyListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ServerKeyListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys'} # type: ignore + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + key_name: str, + **kwargs: Any + ) -> "_models.ServerKey": + """Gets a MySQL Server key. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the MySQL Server key to be retrieved. + :type key_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerKey, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.ServerKey + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + key_name=key_name, + subscription_id=self._config.subscription_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerKey', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + + def _create_or_update_initial( + self, + server_name: str, + key_name: str, + resource_group_name: str, + parameters: "_models.ServerKey", + **kwargs: Any + ) -> "_models.ServerKey": + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerKey') + + request = build_create_or_update_request_initial( + server_name=server_name, + key_name=key_name, + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('ServerKey', pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize('ServerKey', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + + @distributed_trace + def begin_create_or_update( + self, + server_name: str, + key_name: str, + resource_group_name: str, + parameters: "_models.ServerKey", + **kwargs: Any + ) -> LROPoller["_models.ServerKey"]: + """Creates or updates a MySQL Server key. + + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the MySQL Server key to be operated on (updated or created). + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param parameters: The requested MySQL Server key resource state. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerKey + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ServerKey or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerKey] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + server_name=server_name, + key_name=key_name, + resource_group_name=resource_group_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('ServerKey', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + def _delete_initial( + self, + server_name: str, + key_name: str, + resource_group_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + server_name=server_name, + key_name=key_name, + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + + @distributed_trace + def begin_delete( + self, + server_name: str, + key_name: str, + resource_group_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes the MySQL Server key with the given name. + + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the MySQL Server key to be deleted. + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + server_name=server_name, + key_name=key_name, + resource_group_name=resource_group_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_parameters_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_parameters_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..6fe3b08c42b7ceca35eaa4aebc43a274638e25e5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_parameters_operations.py @@ -0,0 +1,212 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_update_configurations_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + +class ServerParametersOperations(object): + """ServerParametersOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _list_update_configurations_initial( + self, + resource_group_name: str, + server_name: str, + value: "_models.ConfigurationListResult", + **kwargs: Any + ) -> Optional["_models.ConfigurationListResult"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ConfigurationListResult"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(value, 'ConfigurationListResult') + + request = build_list_update_configurations_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._list_update_configurations_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _list_update_configurations_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations'} # type: ignore + + + @distributed_trace + def begin_list_update_configurations( + self, + resource_group_name: str, + server_name: str, + value: "_models.ConfigurationListResult", + **kwargs: Any + ) -> LROPoller["_models.ConfigurationListResult"]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param value: The parameters for updating a list of server configuration. + :type value: ~azure.mgmt.rdbms.mysql.models.ConfigurationListResult + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ConfigurationListResult or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._list_update_configurations_initial( + resource_group_name=resource_group_name, + server_name=server_name, + value=value, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_list_update_configurations.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_security_alert_policies_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_security_alert_policies_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b1cc04f6f30e84ce28cdf48de9ad70105d80ab42 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_server_security_alert_policies_operations.py @@ -0,0 +1,423 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "securityAlertPolicyName": _SERIALIZER.url("security_alert_policy_name", security_alert_policy_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_create_or_update_request_initial( + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + subscription_id: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "securityAlertPolicyName": _SERIALIZER.url("security_alert_policy_name", security_alert_policy_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_list_by_server_request( + resource_group_name: str, + server_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class ServerSecurityAlertPoliciesOperations(object): + """ServerSecurityAlertPoliciesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + **kwargs: Any + ) -> "_models.ServerSecurityAlertPolicy": + """Get a server's security alert policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the security alert policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerSecurityAlertPolicy, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + security_alert_policy_name=security_alert_policy_name, + subscription_id=self._config.subscription_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + + def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + parameters: "_models.ServerSecurityAlertPolicy", + **kwargs: Any + ) -> Optional["_models.ServerSecurityAlertPolicy"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ServerSecurityAlertPolicy"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerSecurityAlertPolicy') + + request = build_create_or_update_request_initial( + resource_group_name=resource_group_name, + server_name=server_name, + security_alert_policy_name=security_alert_policy_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + parameters: "_models.ServerSecurityAlertPolicy", + **kwargs: Any + ) -> LROPoller["_models.ServerSecurityAlertPolicy"]: + """Creates or updates a threat detection policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the threat detection policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ServerSecurityAlertPolicy or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + security_alert_policy_name=security_alert_policy_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.ServerSecurityAlertPolicyListResult"]: + """Get the server's threat detection policies. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerSecurityAlertPolicyListResult or the result + of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicyListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicyListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ServerSecurityAlertPolicyListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..3b26a2069733a1bf44799345708ede356b5f097f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_servers_operations.py @@ -0,0 +1,1335 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_create_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_update_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PATCH", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_delete_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="DELETE", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_resource_group_request( + subscription_id: str, + resource_group_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_request( + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/servers') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_restart_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_start_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_stop_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_upgrade_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + +class ServersOperations(object): + """ServersOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForCreate", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerForCreate') + + request = build_create_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._create_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + + @distributed_trace + def begin_create( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForCreate", + **kwargs: Any + ) -> LROPoller["_models.Server"]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerForCreate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Server', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + def _update_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpdateParameters", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerUpdateParameters') + + request = build_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpdateParameters", + **kwargs: Any + ) -> LROPoller["_models.Server"]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpdateParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Server', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + + @distributed_trace + def begin_delete( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.Server": + """Gets information about a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Server, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.Server + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}'} # type: ignore + + + @distributed_trace + def list_by_resource_group( + self, + resource_group_name: str, + **kwargs: Any + ) -> Iterable["_models.ServerListResult"]: + """List all the servers in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + template_url=self.list_by_resource_group.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers'} # type: ignore + + @distributed_trace + def list( + self, + **kwargs: Any + ) -> Iterable["_models.ServerListResult"]: + """List all the servers in a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/servers'} # type: ignore + + def _restart_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_restart_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._restart_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart'} # type: ignore + + + @distributed_trace + def begin_restart( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._restart_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart'} # type: ignore + + def _start_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_start_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._start_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start'} # type: ignore + + + @distributed_trace + def begin_start( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Starts a stopped server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._start_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start'} # type: ignore + + def _stop_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_stop_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._stop_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _stop_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop'} # type: ignore + + + @distributed_trace + def begin_stop( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Stops a running server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._stop_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop'} # type: ignore + + def _upgrade_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpgradeParameters", + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerUpgradeParameters') + + request = build_upgrade_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._upgrade_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _upgrade_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade'} # type: ignore + + + @distributed_trace + def begin_upgrade( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpgradeParameters", + **kwargs: Any + ) -> LROPoller[None]: + """Upgrade server version. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpgradeParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._upgrade_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_upgrade.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_top_query_statistics_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_top_query_statistics_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..41b1270878a9fe3434f000245cab297068722cc9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_top_query_statistics_operations.py @@ -0,0 +1,271 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + query_statistic_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics/{queryStatisticId}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "queryStatisticId": _SERIALIZER.url("query_statistic_id", query_statistic_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + +class TopQueryStatisticsOperations(object): + """TopQueryStatisticsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + query_statistic_id: str, + **kwargs: Any + ) -> "_models.QueryStatistic": + """Retrieve the query statistic for specified identifier. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param query_statistic_id: The Query Statistic identifier. + :type query_statistic_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryStatistic, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.QueryStatistic + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryStatistic"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + query_statistic_id=query_statistic_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('QueryStatistic', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics/{queryStatisticId}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.TopQueryStatisticsInput", + **kwargs: Any + ) -> Iterable["_models.TopQueryStatisticsResultList"]: + """Retrieve the Query-Store top queries for specified metric and aggregation. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for retrieving top query statistics. + :type parameters: ~azure.mgmt.rdbms.mysql.models.TopQueryStatisticsInput + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either TopQueryStatisticsResultList or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.TopQueryStatisticsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + cls = kwargs.pop('cls', None) # type: ClsType["_models.TopQueryStatisticsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + _json = self._serialize.body(parameters, 'TopQueryStatisticsInput') + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + _json = self._serialize.body(parameters, 'TopQueryStatisticsInput') + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("TopQueryStatisticsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_virtual_network_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_virtual_network_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8d0923adacb6993c9f8c0aef589ded942b8905 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_virtual_network_rules_operations.py @@ -0,0 +1,559 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + resource_group_name: str, + server_name: str, + subscription_id: str, + virtual_network_rule_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "virtualNetworkRuleName": _SERIALIZER.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_create_or_update_request_initial( + resource_group_name: str, + server_name: str, + subscription_id: str, + virtual_network_rule_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "virtualNetworkRuleName": _SERIALIZER.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_delete_request_initial( + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "virtualNetworkRuleName": _SERIALIZER.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + return HttpRequest( + method="DELETE", + url=url, + params=query_parameters, + **kwargs + ) + + +def build_list_by_server_request( + resource_group_name: str, + server_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2017-12-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules') + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class VirtualNetworkRulesOperations(object): + """VirtualNetworkRulesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> "_models.VirtualNetworkRule": + """Gets a virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + virtual_network_rule_name=virtual_network_rule_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + + def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: "_models.VirtualNetworkRule", + **kwargs: Any + ) -> Optional["_models.VirtualNetworkRule"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.VirtualNetworkRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'VirtualNetworkRule') + + request = build_create_or_update_request_initial( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + virtual_network_rule_name=virtual_network_rule_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: "_models.VirtualNetworkRule", + **kwargs: Any + ) -> LROPoller["_models.VirtualNetworkRule"]: + """Creates or updates an existing virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :param parameters: The requested virtual Network Rule Resource state. + :type parameters: ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either VirtualNetworkRule or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + subscription_id=self._config.subscription_id, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + + @distributed_trace + def begin_delete( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes the virtual network rule with the given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.VirtualNetworkRuleListResult"]: + """Gets a list of virtual network rules in a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either VirtualNetworkRuleListResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + resource_group_name=resource_group_name, + server_name=server_name, + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("VirtualNetworkRuleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_wait_statistics_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_wait_statistics_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..4631d33e7970155c7a082b6cf6e2c8bd6bef1f9e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql/operations/_wait_statistics_operations.py @@ -0,0 +1,270 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + wait_statistics_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics/{waitStatisticsId}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "waitStatisticsId": _SERIALIZER.url("wait_statistics_id", wait_statistics_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2018-06-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + +class WaitStatisticsOperations(object): + """WaitStatisticsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + wait_statistics_id: str, + **kwargs: Any + ) -> "_models.WaitStatistic": + """Retrieve wait statistics for specified identifier. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param wait_statistics_id: The Wait Statistic identifier. + :type wait_statistics_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: WaitStatistic, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.WaitStatistic + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.WaitStatistic"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + wait_statistics_id=wait_statistics_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('WaitStatistic', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics/{waitStatisticsId}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.WaitStatisticsInput", + **kwargs: Any + ) -> Iterable["_models.WaitStatisticsResultList"]: + """Retrieve wait statistics for specified aggregation window. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for retrieving wait statistics. + :type parameters: ~azure.mgmt.rdbms.mysql.models.WaitStatisticsInput + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either WaitStatisticsResultList or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.WaitStatisticsResultList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + cls = kwargs.pop('cls', None) # type: ClsType["_models.WaitStatisticsResultList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + _json = self._serialize.body(parameters, 'WaitStatisticsInput') + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + _json = self._serialize.body(parameters, 'WaitStatisticsInput') + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("WaitStatisticsResultList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..089186ed748e706ccbbdf60a2d391445b77a6a0d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/__init__.py @@ -0,0 +1,18 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._my_sql_management_client import MySQLManagementClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['MySQLManagementClient'] + +# `._patch.py` is used for handwritten extensions to the generated code +# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +from ._patch import patch_sdk +patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..c9cdf2a724a45c16ad15a042cb916fc9058b6e73 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_configuration.py @@ -0,0 +1,68 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class MySQLManagementClientConfiguration(Configuration): + """Configuration for MySQLManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + super(MySQLManagementClientConfiguration, self).__init__(**kwargs) + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-05-01" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_my_sql_management_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_my_sql_management_client.py new file mode 100644 index 0000000000000000000000000000000000000000..7435cad28bbb9086f1640719cfc3cdd6fdc50d72 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_my_sql_management_client.py @@ -0,0 +1,129 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient +from msrest import Deserializer, Serializer + +from . import models +from ._configuration import MySQLManagementClientConfiguration +from .operations import BackupsOperations, CheckNameAvailabilityOperations, CheckVirtualNetworkSubnetUsageOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, GetPrivateDnsZoneSuffixOperations, LocationBasedCapabilitiesOperations, Operations, ReplicasOperations, ServersOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + +class MySQLManagementClient: + """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure MySQL resources including servers, databases, firewall rules, VNET rules, log files and configurations with new business model. + + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.mysql_flexibleservers.operations.ServersOperations + :ivar replicas: ReplicasOperations operations + :vartype replicas: azure.mgmt.rdbms.mysql_flexibleservers.operations.ReplicasOperations + :ivar backups: BackupsOperations operations + :vartype backups: azure.mgmt.rdbms.mysql_flexibleservers.operations.BackupsOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: + azure.mgmt.rdbms.mysql_flexibleservers.operations.FirewallRulesOperations + :ivar databases: DatabasesOperations operations + :vartype databases: azure.mgmt.rdbms.mysql_flexibleservers.operations.DatabasesOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: + azure.mgmt.rdbms.mysql_flexibleservers.operations.ConfigurationsOperations + :ivar location_based_capabilities: LocationBasedCapabilitiesOperations operations + :vartype location_based_capabilities: + azure.mgmt.rdbms.mysql_flexibleservers.operations.LocationBasedCapabilitiesOperations + :ivar check_virtual_network_subnet_usage: CheckVirtualNetworkSubnetUsageOperations operations + :vartype check_virtual_network_subnet_usage: + azure.mgmt.rdbms.mysql_flexibleservers.operations.CheckVirtualNetworkSubnetUsageOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: + azure.mgmt.rdbms.mysql_flexibleservers.operations.CheckNameAvailabilityOperations + :ivar get_private_dns_zone_suffix: GetPrivateDnsZoneSuffixOperations operations + :vartype get_private_dns_zone_suffix: + azure.mgmt.rdbms.mysql_flexibleservers.operations.GetPrivateDnsZoneSuffixOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.mysql_flexibleservers.operations.Operations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param base_url: Service URL. Default value is 'https://management.azure.com'. + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = MySQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.servers = ServersOperations(self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations(self._client, self._config, self._serialize, self._deserialize) + self.backups = BackupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations(self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_capabilities = LocationBasedCapabilitiesOperations(self._client, self._config, self._serialize, self._deserialize) + self.check_virtual_network_subnet_usage = CheckVirtualNetworkSubnetUsageOperations(self._client, self._config, self._serialize, self._deserialize) + self.check_name_availability = CheckNameAvailabilityOperations(self._client, self._config, self._serialize, self._deserialize) + self.get_private_dns_zone_suffix = GetPrivateDnsZoneSuffixOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + + + def _send_request( + self, + request, # type: HttpRequest + **kwargs: Any + ) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> MySQLManagementClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..74e48ecd07cf36d7740246e19b7fd4a701a5130b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_patch.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# This file is used for handwritten extensions to the generated code. Example: +# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +def patch_sdk(): + pass \ No newline at end of file diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..138f663c53a4e573c9426047e878528c95c6326f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [ + c for c in formatted_components if "{}".format(key.args[0]) not in c + ] + template = "/".join(components) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..c1257f7f4e111146dae88528000dc4841f2ef2aa --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "10.1.0" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..910a198089c91c8b7847113ac5fae1887eb9b197 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/__init__.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._my_sql_management_client import MySQLManagementClient +__all__ = ['MySQLManagementClient'] + +# `._patch.py` is used for handwritten extensions to the generated code +# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +from ._patch import patch_sdk +patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..06793497341dc7604db26668f3fa7d745318af97 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class MySQLManagementClientConfiguration(Configuration): + """Configuration for MySQLManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + super(MySQLManagementClientConfiguration, self).__init__(**kwargs) + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-05-01" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/_my_sql_management_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/_my_sql_management_client.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec1257cbdb0ac43ac4726d9f0c76d81445c4b56 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/_my_sql_management_client.py @@ -0,0 +1,126 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from msrest import Deserializer, Serializer + +from .. import models +from ._configuration import MySQLManagementClientConfiguration +from .operations import BackupsOperations, CheckNameAvailabilityOperations, CheckVirtualNetworkSubnetUsageOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, GetPrivateDnsZoneSuffixOperations, LocationBasedCapabilitiesOperations, Operations, ReplicasOperations, ServersOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class MySQLManagementClient: + """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure MySQL resources including servers, databases, firewall rules, VNET rules, log files and configurations with new business model. + + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.ServersOperations + :ivar replicas: ReplicasOperations operations + :vartype replicas: azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.ReplicasOperations + :ivar backups: BackupsOperations operations + :vartype backups: azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.BackupsOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: + azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.FirewallRulesOperations + :ivar databases: DatabasesOperations operations + :vartype databases: azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.DatabasesOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: + azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.ConfigurationsOperations + :ivar location_based_capabilities: LocationBasedCapabilitiesOperations operations + :vartype location_based_capabilities: + azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.LocationBasedCapabilitiesOperations + :ivar check_virtual_network_subnet_usage: CheckVirtualNetworkSubnetUsageOperations operations + :vartype check_virtual_network_subnet_usage: + azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.CheckVirtualNetworkSubnetUsageOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: + azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.CheckNameAvailabilityOperations + :ivar get_private_dns_zone_suffix: GetPrivateDnsZoneSuffixOperations operations + :vartype get_private_dns_zone_suffix: + azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.GetPrivateDnsZoneSuffixOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.Operations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param base_url: Service URL. Default value is 'https://management.azure.com'. + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = MySQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.servers = ServersOperations(self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations(self._client, self._config, self._serialize, self._deserialize) + self.backups = BackupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations(self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_capabilities = LocationBasedCapabilitiesOperations(self._client, self._config, self._serialize, self._deserialize) + self.check_virtual_network_subnet_usage = CheckVirtualNetworkSubnetUsageOperations(self._client, self._config, self._serialize, self._deserialize) + self.check_name_availability = CheckNameAvailabilityOperations(self._client, self._config, self._serialize, self._deserialize) + self.get_private_dns_zone_suffix = GetPrivateDnsZoneSuffixOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + + + def _send_request( + self, + request: HttpRequest, + **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "MySQLManagementClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..74e48ecd07cf36d7740246e19b7fd4a701a5130b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/_patch.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# This file is used for handwritten extensions to the generated code. Example: +# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +def patch_sdk(): + pass \ No newline at end of file diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5d881e8f807c8a3b06636ce6564f65201f4155c6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/__init__.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._servers_operations import ServersOperations +from ._replicas_operations import ReplicasOperations +from ._backups_operations import BackupsOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._databases_operations import DatabasesOperations +from ._configurations_operations import ConfigurationsOperations +from ._location_based_capabilities_operations import LocationBasedCapabilitiesOperations +from ._check_virtual_network_subnet_usage_operations import CheckVirtualNetworkSubnetUsageOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._get_private_dns_zone_suffix_operations import GetPrivateDnsZoneSuffixOperations +from ._operations import Operations + +__all__ = [ + 'ServersOperations', + 'ReplicasOperations', + 'BackupsOperations', + 'FirewallRulesOperations', + 'DatabasesOperations', + 'ConfigurationsOperations', + 'LocationBasedCapabilitiesOperations', + 'CheckVirtualNetworkSubnetUsageOperations', + 'CheckNameAvailabilityOperations', + 'GetPrivateDnsZoneSuffixOperations', + 'Operations', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_backups_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_backups_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..f011ac22688d181dc596c183814e07e635194b65 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_backups_operations.py @@ -0,0 +1,177 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._backups_operations import build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class BackupsOperations: + """BackupsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + backup_name: str, + **kwargs: Any + ) -> "_models.ServerBackup": + """List all the backups for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param backup_name: The name of the backup. + :type backup_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerBackup, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackup + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerBackup"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + backup_name=backup_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerBackup', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerBackupListResult"]: + """List all the backups for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerBackupListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackupListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerBackupListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ServerBackupListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_name_availability_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_name_availability_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..29679d2099784e42bb0ecb944af6bfddfb4e91f8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_name_availability_operations.py @@ -0,0 +1,102 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._check_name_availability_operations import build_execute_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class CheckNameAvailabilityOperations: + """CheckNameAvailabilityOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def execute( + self, + location_name: str, + name_availability_request: "_models.NameAvailabilityRequest", + **kwargs: Any + ) -> "_models.NameAvailability": + """Check the availability of name for server. + + :param location_name: The name of the location. + :type location_name: str + :param name_availability_request: The required parameters for checking if server name is + available. + :type name_availability_request: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailabilityRequest + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + + request = build_execute_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + content_type=content_type, + json=_json, + template_url=self.execute.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('NameAvailability', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkNameAvailability'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_virtual_network_subnet_usage_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_virtual_network_subnet_usage_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..629ffd422c6a6f768dad0fb1db6eff713682b7f8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_virtual_network_subnet_usage_operations.py @@ -0,0 +1,101 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._check_virtual_network_subnet_usage_operations import build_execute_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class CheckVirtualNetworkSubnetUsageOperations: + """CheckVirtualNetworkSubnetUsageOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def execute( + self, + location_name: str, + parameters: "_models.VirtualNetworkSubnetUsageParameter", + **kwargs: Any + ) -> "_models.VirtualNetworkSubnetUsageResult": + """Get virtual network subnet usage for a given vNet resource id. + + :param location_name: The name of the location. + :type location_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkSubnetUsageResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkSubnetUsageResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'VirtualNetworkSubnetUsageParameter') + + request = build_execute_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + content_type=content_type, + json=_json, + template_url=self.execute.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('VirtualNetworkSubnetUsageResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkVirtualNetworkSubnetUsage'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_configurations_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_configurations_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..f37735668647ea1d38deeb082f885e532ba059ad --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_configurations_operations.py @@ -0,0 +1,424 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._configurations_operations import build_batch_update_request_initial, build_get_request, build_list_by_server_request, build_update_request_initial +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ConfigurationsOperations: + """ConfigurationsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _update_initial( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> Optional["_models.Configuration"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'Configuration') + + request = build_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + content_type=content_type, + json=_json, + template_url=self._update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> AsyncLROPoller["_models.Configuration"]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Configuration or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Configuration', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + **kwargs: Any + ) -> "_models.Configuration": + """Gets information about a configuration of server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Configuration, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + + async def _batch_update_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ConfigurationListForBatchUpdate", + **kwargs: Any + ) -> Optional["_models.ConfigurationListResult"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ConfigurationListResult"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ConfigurationListForBatchUpdate') + + request = build_batch_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._batch_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _batch_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations'} # type: ignore + + + @distributed_trace_async + async def begin_batch_update( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ConfigurationListForBatchUpdate", + **kwargs: Any + ) -> AsyncLROPoller["_models.ConfigurationListResult"]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The parameters for updating a list of server configuration. + :type parameters: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListForBatchUpdate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ConfigurationListResult or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._batch_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_batch_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations'} # type: ignore + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ConfigurationListResult"]: + """List all the configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConfigurationListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_databases_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_databases_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..082e03065850761197296896cf86f6d362d0b8fe --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_databases_operations.py @@ -0,0 +1,408 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._databases_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class DatabasesOperations: + """DatabasesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> Optional["_models.Database"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Database"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'Database') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Database', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> AsyncLROPoller["_models.Database"]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Database + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Database or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Database', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace_async + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> "_models.Database": + """Gets information about a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Database, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Database + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.DatabaseListResult"]: + """List all the databases in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DatabaseListResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.DatabaseListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.DatabaseListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DatabaseListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_firewall_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_firewall_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d0cf5ab83497e3ce1bf0cd31bd9f25c157aac54d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_firewall_rules_operations.py @@ -0,0 +1,409 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._firewall_rules_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class FirewallRulesOperations: + """FirewallRulesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> Optional["_models.FirewallRule"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FirewallRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'FirewallRule') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> AsyncLROPoller["_models.FirewallRule"]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('FirewallRule', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace_async + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> "_models.FirewallRule": + """Gets information about a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FirewallRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.FirewallRuleListResult"]: + """List all the firewall rules in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FirewallRuleListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("FirewallRuleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..18b746c106d1828b13122fa3859802030c176814 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py @@ -0,0 +1,87 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._get_private_dns_zone_suffix_operations import build_execute_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class GetPrivateDnsZoneSuffixOperations: + """GetPrivateDnsZoneSuffixOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace_async + async def execute( + self, + **kwargs: Any + ) -> "_models.GetPrivateDnsZoneSuffixResponse": + """Get private DNS zone suffix in the cloud. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GetPrivateDnsZoneSuffixResponse, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.GetPrivateDnsZoneSuffixResponse + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.GetPrivateDnsZoneSuffixResponse"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_execute_request( + template_url=self.execute.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('GetPrivateDnsZoneSuffixResponse', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + execute.metadata = {'url': '/providers/Microsoft.DBforMySQL/getPrivateDnsZoneSuffix'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_location_based_capabilities_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_location_based_capabilities_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..e728eda1204bc1b363d2e34c647b8a5e22892406 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_location_based_capabilities_operations.py @@ -0,0 +1,117 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._location_based_capabilities_operations import build_list_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedCapabilitiesOperations: + """LocationBasedCapabilitiesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + location_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.CapabilitiesListResult"]: + """Get capabilities at specified location in a given subscription. + + :param location_name: The name of the location. + :type location_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either CapabilitiesListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.CapabilitiesListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.CapabilitiesListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("CapabilitiesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/capabilities'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb6f75b7f0362aedd1735940303a49771e719bf --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_operations.py @@ -0,0 +1,109 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class Operations: + """Operations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.OperationListResult"]: + """Lists all of the available REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either OperationListResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.OperationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.DBforMySQL/operations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_replicas_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_replicas_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..9e149de0da021256765292fc063cbf291f1dc938 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_replicas_operations.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._replicas_operations import build_list_by_server_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ReplicasOperations: + """ReplicasOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the replicas for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/replicas'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..02fa7b6240fe9be0b3417bb3831efd3c1fe5d7fc --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_servers_operations.py @@ -0,0 +1,968 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._servers_operations import build_create_request_initial, build_delete_request_initial, build_failover_request_initial, build_get_request, build_list_by_resource_group_request, build_list_request, build_restart_request_initial, build_start_request_initial, build_stop_request_initial, build_update_request_initial +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServersOperations: + """ServersOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.Server", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'Server') + + request = build_create_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._create_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + + @distributed_trace_async + async def begin_create( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.Server", + **kwargs: Any + ) -> AsyncLROPoller["_models.Server"]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Server + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Server', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + async def _update_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForUpdate", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerForUpdate') + + request = build_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForUpdate", + **kwargs: Any + ) -> AsyncLROPoller["_models.Server"]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerForUpdate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Server', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + + @distributed_trace_async + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.Server": + """Gets information about a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Server, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Server + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + + @distributed_trace + def list_by_resource_group( + self, + resource_group_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the servers in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + template_url=self.list_by_resource_group.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers'} # type: ignore + + @distributed_trace + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the servers in a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/flexibleServers'} # type: ignore + + async def _failover_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_failover_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._failover_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _failover_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover'} # type: ignore + + + @distributed_trace_async + async def begin_failover( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Manual failover a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._failover_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_failover.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover'} # type: ignore + + async def _restart_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerRestartParameter", + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerRestartParameter') + + request = build_restart_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._restart_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart'} # type: ignore + + + @distributed_trace_async + async def begin_restart( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerRestartParameter", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for restarting a server. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerRestartParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._restart_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart'} # type: ignore + + async def _start_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_start_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._start_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start'} # type: ignore + + + @distributed_trace_async + async def begin_start( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Starts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._start_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start'} # type: ignore + + async def _stop_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_stop_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._stop_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _stop_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop'} # type: ignore + + + @distributed_trace_async + async def begin_stop( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Stops a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._stop_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b7d16c6b0727c476a6458a2723d0f7ac76b0560e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/models/__init__.py @@ -0,0 +1,131 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import Backup +from ._models_py3 import CapabilitiesListResult +from ._models_py3 import CapabilityProperties +from ._models_py3 import Configuration +from ._models_py3 import ConfigurationForBatchUpdate +from ._models_py3 import ConfigurationListForBatchUpdate +from ._models_py3 import ConfigurationListResult +from ._models_py3 import DataEncryption +from ._models_py3 import Database +from ._models_py3 import DatabaseListResult +from ._models_py3 import DelegatedSubnetUsage +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorResponse +from ._models_py3 import FirewallRule +from ._models_py3 import FirewallRuleListResult +from ._models_py3 import GetPrivateDnsZoneSuffixResponse +from ._models_py3 import HighAvailability +from ._models_py3 import Identity +from ._models_py3 import MaintenanceWindow +from ._models_py3 import NameAvailability +from ._models_py3 import NameAvailabilityRequest +from ._models_py3 import Network +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import ProxyResource +from ._models_py3 import Resource +from ._models_py3 import Server +from ._models_py3 import ServerBackup +from ._models_py3 import ServerBackupListResult +from ._models_py3 import ServerEditionCapability +from ._models_py3 import ServerForUpdate +from ._models_py3 import ServerListResult +from ._models_py3 import ServerRestartParameter +from ._models_py3 import ServerVersionCapability +from ._models_py3 import Sku +from ._models_py3 import SkuCapability +from ._models_py3 import Storage +from ._models_py3 import StorageEditionCapability +from ._models_py3 import SystemData +from ._models_py3 import TrackedResource +from ._models_py3 import UserAssignedIdentity +from ._models_py3 import VirtualNetworkSubnetUsageParameter +from ._models_py3 import VirtualNetworkSubnetUsageResult + + +from ._my_sql_management_client_enums import ( + ConfigurationSource, + CreateMode, + CreatedByType, + DataEncryptionType, + EnableStatusEnum, + HighAvailabilityMode, + HighAvailabilityState, + IsConfigPendingRestart, + IsDynamicConfig, + IsReadOnly, + ReplicationRole, + ServerState, + ServerVersion, + SkuTier, +) + +__all__ = [ + 'Backup', + 'CapabilitiesListResult', + 'CapabilityProperties', + 'Configuration', + 'ConfigurationForBatchUpdate', + 'ConfigurationListForBatchUpdate', + 'ConfigurationListResult', + 'DataEncryption', + 'Database', + 'DatabaseListResult', + 'DelegatedSubnetUsage', + 'ErrorAdditionalInfo', + 'ErrorResponse', + 'FirewallRule', + 'FirewallRuleListResult', + 'GetPrivateDnsZoneSuffixResponse', + 'HighAvailability', + 'Identity', + 'MaintenanceWindow', + 'NameAvailability', + 'NameAvailabilityRequest', + 'Network', + 'Operation', + 'OperationDisplay', + 'OperationListResult', + 'ProxyResource', + 'Resource', + 'Server', + 'ServerBackup', + 'ServerBackupListResult', + 'ServerEditionCapability', + 'ServerForUpdate', + 'ServerListResult', + 'ServerRestartParameter', + 'ServerVersionCapability', + 'Sku', + 'SkuCapability', + 'Storage', + 'StorageEditionCapability', + 'SystemData', + 'TrackedResource', + 'UserAssignedIdentity', + 'VirtualNetworkSubnetUsageParameter', + 'VirtualNetworkSubnetUsageResult', + 'ConfigurationSource', + 'CreateMode', + 'CreatedByType', + 'DataEncryptionType', + 'EnableStatusEnum', + 'HighAvailabilityMode', + 'HighAvailabilityState', + 'IsConfigPendingRestart', + 'IsDynamicConfig', + 'IsReadOnly', + 'ReplicationRole', + 'ServerState', + 'ServerVersion', + 'SkuTier', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..f7995e3da5a1e6d0838dd11bac3c3663b437302b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/models/_models_py3.py @@ -0,0 +1,2083 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import Any, Dict, List, Optional, Union + +import msrest.serialization + +from ._my_sql_management_client_enums import * + + +class Backup(msrest.serialization.Model): + """Storage Profile properties of a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar backup_retention_days: Backup retention days for the server. + :vartype backup_retention_days: int + :ivar geo_redundant_backup: Whether or not geo redundant backup is enabled. Possible values + include: "Enabled", "Disabled". + :vartype geo_redundant_backup: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum + :ivar earliest_restore_date: Earliest restore point creation time (ISO8601 format). + :vartype earliest_restore_date: ~datetime.datetime + """ + + _validation = { + 'earliest_restore_date': {'readonly': True}, + } + + _attribute_map = { + 'backup_retention_days': {'key': 'backupRetentionDays', 'type': 'int'}, + 'geo_redundant_backup': {'key': 'geoRedundantBackup', 'type': 'str'}, + 'earliest_restore_date': {'key': 'earliestRestoreDate', 'type': 'iso-8601'}, + } + + def __init__( + self, + *, + backup_retention_days: Optional[int] = None, + geo_redundant_backup: Optional[Union[str, "EnableStatusEnum"]] = None, + **kwargs + ): + """ + :keyword backup_retention_days: Backup retention days for the server. + :paramtype backup_retention_days: int + :keyword geo_redundant_backup: Whether or not geo redundant backup is enabled. Possible values + include: "Enabled", "Disabled". + :paramtype geo_redundant_backup: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum + """ + super(Backup, self).__init__(**kwargs) + self.backup_retention_days = backup_retention_days + self.geo_redundant_backup = geo_redundant_backup + self.earliest_restore_date = None + + +class CapabilitiesListResult(msrest.serialization.Model): + """location capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: A list of supported capabilities. + :vartype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.CapabilityProperties] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[CapabilityProperties]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(CapabilitiesListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class CapabilityProperties(msrest.serialization.Model): + """Location capabilities. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar zone: zone name. + :vartype zone: str + :ivar supported_ha_mode: Supported high availability mode. + :vartype supported_ha_mode: list[str] + :ivar supported_geo_backup_regions: supported geo backup regions. + :vartype supported_geo_backup_regions: list[str] + :ivar supported_flexible_server_editions: A list of supported flexible server editions. + :vartype supported_flexible_server_editions: + list[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerEditionCapability] + """ + + _validation = { + 'zone': {'readonly': True}, + 'supported_ha_mode': {'readonly': True}, + 'supported_geo_backup_regions': {'readonly': True}, + 'supported_flexible_server_editions': {'readonly': True}, + } + + _attribute_map = { + 'zone': {'key': 'zone', 'type': 'str'}, + 'supported_ha_mode': {'key': 'supportedHAMode', 'type': '[str]'}, + 'supported_geo_backup_regions': {'key': 'supportedGeoBackupRegions', 'type': '[str]'}, + 'supported_flexible_server_editions': {'key': 'supportedFlexibleServerEditions', 'type': '[ServerEditionCapability]'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(CapabilityProperties, self).__init__(**kwargs) + self.zone = None + self.supported_ha_mode = None + self.supported_geo_backup_regions = None + self.supported_flexible_server_editions = None + + +class Resource(msrest.serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(ProxyResource, self).__init__(**kwargs) + + +class Configuration(ProxyResource): + """Represents a Configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.mysql_flexibleservers.models.SystemData + :ivar value: Value of the configuration. + :vartype value: str + :ivar description: Description of the configuration. + :vartype description: str + :ivar default_value: Default value of the configuration. + :vartype default_value: str + :ivar data_type: Data type of the configuration. + :vartype data_type: str + :ivar allowed_values: Allowed values of the configuration. + :vartype allowed_values: str + :ivar source: Source of the configuration. Possible values include: "system-default", + "user-override". + :vartype source: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationSource + :ivar is_read_only: If is the configuration read only. Possible values include: "True", + "False". + :vartype is_read_only: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.IsReadOnly + :ivar is_config_pending_restart: If is the configuration pending restart or not. Possible + values include: "True", "False". + :vartype is_config_pending_restart: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.IsConfigPendingRestart + :ivar is_dynamic_config: If is the configuration dynamic. Possible values include: "True", + "False". + :vartype is_dynamic_config: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.IsDynamicConfig + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'description': {'readonly': True}, + 'default_value': {'readonly': True}, + 'data_type': {'readonly': True}, + 'allowed_values': {'readonly': True}, + 'is_read_only': {'readonly': True}, + 'is_config_pending_restart': {'readonly': True}, + 'is_dynamic_config': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'value': {'key': 'properties.value', 'type': 'str'}, + 'description': {'key': 'properties.description', 'type': 'str'}, + 'default_value': {'key': 'properties.defaultValue', 'type': 'str'}, + 'data_type': {'key': 'properties.dataType', 'type': 'str'}, + 'allowed_values': {'key': 'properties.allowedValues', 'type': 'str'}, + 'source': {'key': 'properties.source', 'type': 'str'}, + 'is_read_only': {'key': 'properties.isReadOnly', 'type': 'str'}, + 'is_config_pending_restart': {'key': 'properties.isConfigPendingRestart', 'type': 'str'}, + 'is_dynamic_config': {'key': 'properties.isDynamicConfig', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[str] = None, + source: Optional[Union[str, "ConfigurationSource"]] = None, + **kwargs + ): + """ + :keyword value: Value of the configuration. + :paramtype value: str + :keyword source: Source of the configuration. Possible values include: "system-default", + "user-override". + :paramtype source: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationSource + """ + super(Configuration, self).__init__(**kwargs) + self.system_data = None + self.value = value + self.description = None + self.default_value = None + self.data_type = None + self.allowed_values = None + self.source = source + self.is_read_only = None + self.is_config_pending_restart = None + self.is_dynamic_config = None + + +class ConfigurationForBatchUpdate(msrest.serialization.Model): + """Represents a Configuration. + + :ivar name: Name of the configuration. + :vartype name: str + :ivar value: Value of the configuration. + :vartype value: str + :ivar source: Source of the configuration. + :vartype source: str + """ + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'value': {'key': 'properties.value', 'type': 'str'}, + 'source': {'key': 'properties.source', 'type': 'str'}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + value: Optional[str] = None, + source: Optional[str] = None, + **kwargs + ): + """ + :keyword name: Name of the configuration. + :paramtype name: str + :keyword value: Value of the configuration. + :paramtype value: str + :keyword source: Source of the configuration. + :paramtype source: str + """ + super(ConfigurationForBatchUpdate, self).__init__(**kwargs) + self.name = name + self.value = value + self.source = source + + +class ConfigurationListForBatchUpdate(msrest.serialization.Model): + """A list of server configurations to update. + + :ivar value: The list of server configurations. + :vartype value: + list[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationForBatchUpdate] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ConfigurationForBatchUpdate]'}, + } + + def __init__( + self, + *, + value: Optional[List["ConfigurationForBatchUpdate"]] = None, + **kwargs + ): + """ + :keyword value: The list of server configurations. + :paramtype value: + list[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationForBatchUpdate] + """ + super(ConfigurationListForBatchUpdate, self).__init__(**kwargs) + self.value = value + + +class ConfigurationListResult(msrest.serialization.Model): + """A list of server configurations. + + :ivar value: The list of server configurations. + :vartype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] + :ivar next_link: The link used to get the next page of operations. + :vartype next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Configuration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["Configuration"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: The list of server configurations. + :paramtype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] + :keyword next_link: The link used to get the next page of operations. + :paramtype next_link: str + """ + super(ConfigurationListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class Database(ProxyResource): + """Represents a Database. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.mysql_flexibleservers.models.SystemData + :ivar charset: The charset of the database. + :vartype charset: str + :ivar collation: The collation of the database. + :vartype collation: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'charset': {'key': 'properties.charset', 'type': 'str'}, + 'collation': {'key': 'properties.collation', 'type': 'str'}, + } + + def __init__( + self, + *, + charset: Optional[str] = None, + collation: Optional[str] = None, + **kwargs + ): + """ + :keyword charset: The charset of the database. + :paramtype charset: str + :keyword collation: The collation of the database. + :paramtype collation: str + """ + super(Database, self).__init__(**kwargs) + self.system_data = None + self.charset = charset + self.collation = collation + + +class DatabaseListResult(msrest.serialization.Model): + """A List of databases. + + :ivar value: The list of databases housed in a server. + :vartype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] + :ivar next_link: The link used to get the next page of operations. + :vartype next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Database]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["Database"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: The list of databases housed in a server. + :paramtype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] + :keyword next_link: The link used to get the next page of operations. + :paramtype next_link: str + """ + super(DatabaseListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class DataEncryption(msrest.serialization.Model): + """The date encryption for cmk. + + :ivar primary_user_assigned_identity_id: Primary user identity resource id. + :vartype primary_user_assigned_identity_id: str + :ivar primary_key_uri: Primary key uri. + :vartype primary_key_uri: str + :ivar geo_backup_user_assigned_identity_id: Geo backup user identity resource id as identity + can't cross region, need identity in same region as geo backup. + :vartype geo_backup_user_assigned_identity_id: str + :ivar geo_backup_key_uri: Geo backup key uri as key vault can't cross region, need cmk in same + region as geo backup. + :vartype geo_backup_key_uri: str + :ivar type: The key type, AzureKeyVault for enable cmk, SystemManaged for disable cmk. Possible + values include: "AzureKeyVault", "SystemManaged". + :vartype type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.DataEncryptionType + """ + + _attribute_map = { + 'primary_user_assigned_identity_id': {'key': 'primaryUserAssignedIdentityId', 'type': 'str'}, + 'primary_key_uri': {'key': 'primaryKeyUri', 'type': 'str'}, + 'geo_backup_user_assigned_identity_id': {'key': 'geoBackupUserAssignedIdentityId', 'type': 'str'}, + 'geo_backup_key_uri': {'key': 'geoBackupKeyUri', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + primary_user_assigned_identity_id: Optional[str] = None, + primary_key_uri: Optional[str] = None, + geo_backup_user_assigned_identity_id: Optional[str] = None, + geo_backup_key_uri: Optional[str] = None, + type: Optional[Union[str, "DataEncryptionType"]] = None, + **kwargs + ): + """ + :keyword primary_user_assigned_identity_id: Primary user identity resource id. + :paramtype primary_user_assigned_identity_id: str + :keyword primary_key_uri: Primary key uri. + :paramtype primary_key_uri: str + :keyword geo_backup_user_assigned_identity_id: Geo backup user identity resource id as identity + can't cross region, need identity in same region as geo backup. + :paramtype geo_backup_user_assigned_identity_id: str + :keyword geo_backup_key_uri: Geo backup key uri as key vault can't cross region, need cmk in + same region as geo backup. + :paramtype geo_backup_key_uri: str + :keyword type: The key type, AzureKeyVault for enable cmk, SystemManaged for disable cmk. + Possible values include: "AzureKeyVault", "SystemManaged". + :paramtype type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.DataEncryptionType + """ + super(DataEncryption, self).__init__(**kwargs) + self.primary_user_assigned_identity_id = primary_user_assigned_identity_id + self.primary_key_uri = primary_key_uri + self.geo_backup_user_assigned_identity_id = geo_backup_user_assigned_identity_id + self.geo_backup_key_uri = geo_backup_key_uri + self.type = type + + +class DelegatedSubnetUsage(msrest.serialization.Model): + """Delegated subnet usage data. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar subnet_name: name of the subnet. + :vartype subnet_name: str + :ivar usage: Number of used delegated subnets. + :vartype usage: long + """ + + _validation = { + 'subnet_name': {'readonly': True}, + 'usage': {'readonly': True}, + } + + _attribute_map = { + 'subnet_name': {'key': 'subnetName', 'type': 'str'}, + 'usage': {'key': 'usage', 'type': 'long'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(DelegatedSubnetUsage, self).__init__(**kwargs) + self.subnet_name = None + self.usage = None + + +class ErrorAdditionalInfo(msrest.serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorResponse(msrest.serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.mgmt.rdbms.mysql_flexibleservers.models.ErrorAdditionalInfo] + """ + + _validation = { + 'code': {'readonly': True}, + 'message': {'readonly': True}, + 'target': {'readonly': True}, + 'details': {'readonly': True}, + 'additional_info': {'readonly': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'target': {'key': 'target', 'type': 'str'}, + 'details': {'key': 'details', 'type': '[ErrorResponse]'}, + 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(ErrorResponse, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class FirewallRule(ProxyResource): + """Represents a server firewall rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.mysql_flexibleservers.models.SystemData + :ivar start_ip_address: Required. The start IP address of the server firewall rule. Must be + IPv4 format. + :vartype start_ip_address: str + :ivar end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 + format. + :vartype end_ip_address: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'start_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + 'end_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'start_ip_address': {'key': 'properties.startIpAddress', 'type': 'str'}, + 'end_ip_address': {'key': 'properties.endIpAddress', 'type': 'str'}, + } + + def __init__( + self, + *, + start_ip_address: str, + end_ip_address: str, + **kwargs + ): + """ + :keyword start_ip_address: Required. The start IP address of the server firewall rule. Must be + IPv4 format. + :paramtype start_ip_address: str + :keyword end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 + format. + :paramtype end_ip_address: str + """ + super(FirewallRule, self).__init__(**kwargs) + self.system_data = None + self.start_ip_address = start_ip_address + self.end_ip_address = end_ip_address + + +class FirewallRuleListResult(msrest.serialization.Model): + """A list of firewall rules. + + :ivar value: The list of firewall rules in a server. + :vartype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] + :ivar next_link: The link used to get the next page of operations. + :vartype next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FirewallRule]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["FirewallRule"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: The list of firewall rules in a server. + :paramtype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] + :keyword next_link: The link used to get the next page of operations. + :paramtype next_link: str + """ + super(FirewallRuleListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class GetPrivateDnsZoneSuffixResponse(msrest.serialization.Model): + """The response of get private dns zone suffix. + + :ivar private_dns_zone_suffix: Represents the private DNS zone suffix. + :vartype private_dns_zone_suffix: str + """ + + _attribute_map = { + 'private_dns_zone_suffix': {'key': 'privateDnsZoneSuffix', 'type': 'str'}, + } + + def __init__( + self, + *, + private_dns_zone_suffix: Optional[str] = None, + **kwargs + ): + """ + :keyword private_dns_zone_suffix: Represents the private DNS zone suffix. + :paramtype private_dns_zone_suffix: str + """ + super(GetPrivateDnsZoneSuffixResponse, self).__init__(**kwargs) + self.private_dns_zone_suffix = private_dns_zone_suffix + + +class HighAvailability(msrest.serialization.Model): + """Network related properties of a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar mode: High availability mode for a server. Possible values include: "Disabled", + "ZoneRedundant", "SameZone". + :vartype mode: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.HighAvailabilityMode + :ivar state: The state of server high availability. Possible values include: "NotEnabled", + "CreatingStandby", "Healthy", "FailingOver", "RemovingStandby". + :vartype state: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.HighAvailabilityState + :ivar standby_availability_zone: Availability zone of the standby server. + :vartype standby_availability_zone: str + """ + + _validation = { + 'state': {'readonly': True}, + } + + _attribute_map = { + 'mode': {'key': 'mode', 'type': 'str'}, + 'state': {'key': 'state', 'type': 'str'}, + 'standby_availability_zone': {'key': 'standbyAvailabilityZone', 'type': 'str'}, + } + + def __init__( + self, + *, + mode: Optional[Union[str, "HighAvailabilityMode"]] = None, + standby_availability_zone: Optional[str] = None, + **kwargs + ): + """ + :keyword mode: High availability mode for a server. Possible values include: "Disabled", + "ZoneRedundant", "SameZone". + :paramtype mode: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.HighAvailabilityMode + :keyword standby_availability_zone: Availability zone of the standby server. + :paramtype standby_availability_zone: str + """ + super(HighAvailability, self).__init__(**kwargs) + self.mode = mode + self.state = None + self.standby_availability_zone = standby_availability_zone + + +class Identity(msrest.serialization.Model): + """Properties to configure Identity for Bring your Own Keys. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: ObjectId from the KeyVault. + :vartype principal_id: str + :ivar tenant_id: TenantId from the KeyVault. + :vartype tenant_id: str + :ivar type: Type of managed service identity. The only acceptable values to pass in are None + and "UserAssigned". The default value is None. + :vartype type: str + :ivar user_assigned_identities: Metadata of user assigned identity. + :vartype user_assigned_identities: dict[str, any] + """ + + _validation = { + 'principal_id': {'readonly': True}, + 'tenant_id': {'readonly': True}, + } + + _attribute_map = { + 'principal_id': {'key': 'principalId', 'type': 'str'}, + 'tenant_id': {'key': 'tenantId', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'user_assigned_identities': {'key': 'userAssignedIdentities', 'type': '{object}'}, + } + + def __init__( + self, + *, + type: Optional[str] = None, + user_assigned_identities: Optional[Dict[str, Any]] = None, + **kwargs + ): + """ + :keyword type: Type of managed service identity. The only acceptable values to pass in are None + and "UserAssigned". The default value is None. + :paramtype type: str + :keyword user_assigned_identities: Metadata of user assigned identity. + :paramtype user_assigned_identities: dict[str, any] + """ + super(Identity, self).__init__(**kwargs) + self.principal_id = None + self.tenant_id = None + self.type = type + self.user_assigned_identities = user_assigned_identities + + +class MaintenanceWindow(msrest.serialization.Model): + """Maintenance window of a server. + + :ivar custom_window: indicates whether custom window is enabled or disabled. + :vartype custom_window: str + :ivar start_hour: start hour for maintenance window. + :vartype start_hour: int + :ivar start_minute: start minute for maintenance window. + :vartype start_minute: int + :ivar day_of_week: day of week for maintenance window. + :vartype day_of_week: int + """ + + _attribute_map = { + 'custom_window': {'key': 'customWindow', 'type': 'str'}, + 'start_hour': {'key': 'startHour', 'type': 'int'}, + 'start_minute': {'key': 'startMinute', 'type': 'int'}, + 'day_of_week': {'key': 'dayOfWeek', 'type': 'int'}, + } + + def __init__( + self, + *, + custom_window: Optional[str] = None, + start_hour: Optional[int] = None, + start_minute: Optional[int] = None, + day_of_week: Optional[int] = None, + **kwargs + ): + """ + :keyword custom_window: indicates whether custom window is enabled or disabled. + :paramtype custom_window: str + :keyword start_hour: start hour for maintenance window. + :paramtype start_hour: int + :keyword start_minute: start minute for maintenance window. + :paramtype start_minute: int + :keyword day_of_week: day of week for maintenance window. + :paramtype day_of_week: int + """ + super(MaintenanceWindow, self).__init__(**kwargs) + self.custom_window = custom_window + self.start_hour = start_hour + self.start_minute = start_minute + self.day_of_week = day_of_week + + +class NameAvailability(msrest.serialization.Model): + """Represents a resource name availability. + + :ivar message: Error Message. + :vartype message: str + :ivar name_available: Indicates whether the resource name is available. + :vartype name_available: bool + :ivar reason: Reason for name being unavailable. + :vartype reason: str + """ + + _attribute_map = { + 'message': {'key': 'message', 'type': 'str'}, + 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, + 'reason': {'key': 'reason', 'type': 'str'}, + } + + def __init__( + self, + *, + message: Optional[str] = None, + name_available: Optional[bool] = None, + reason: Optional[str] = None, + **kwargs + ): + """ + :keyword message: Error Message. + :paramtype message: str + :keyword name_available: Indicates whether the resource name is available. + :paramtype name_available: bool + :keyword reason: Reason for name being unavailable. + :paramtype reason: str + """ + super(NameAvailability, self).__init__(**kwargs) + self.message = message + self.name_available = name_available + self.reason = reason + + +class NameAvailabilityRequest(msrest.serialization.Model): + """Request from client to check resource name availability. + + All required parameters must be populated in order to send to Azure. + + :ivar name: Required. Resource name to verify. + :vartype name: str + :ivar type: Resource type used for verification. + :vartype type: str + """ + + _validation = { + 'name': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + name: str, + type: Optional[str] = None, + **kwargs + ): + """ + :keyword name: Required. Resource name to verify. + :paramtype name: str + :keyword type: Resource type used for verification. + :paramtype type: str + """ + super(NameAvailabilityRequest, self).__init__(**kwargs) + self.name = name + self.type = type + + +class Network(msrest.serialization.Model): + """Network related properties of a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar public_network_access: Whether or not public network access is allowed for this server. + Value is 'Disabled' when server has VNet integration. Possible values include: "Enabled", + "Disabled". + :vartype public_network_access: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum + :ivar delegated_subnet_resource_id: Delegated subnet resource id used to setup vnet for a + server. + :vartype delegated_subnet_resource_id: str + :ivar private_dns_zone_resource_id: Private DNS zone resource id. + :vartype private_dns_zone_resource_id: str + """ + + _validation = { + 'public_network_access': {'readonly': True}, + } + + _attribute_map = { + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'delegated_subnet_resource_id': {'key': 'delegatedSubnetResourceId', 'type': 'str'}, + 'private_dns_zone_resource_id': {'key': 'privateDnsZoneResourceId', 'type': 'str'}, + } + + def __init__( + self, + *, + delegated_subnet_resource_id: Optional[str] = None, + private_dns_zone_resource_id: Optional[str] = None, + **kwargs + ): + """ + :keyword delegated_subnet_resource_id: Delegated subnet resource id used to setup vnet for a + server. + :paramtype delegated_subnet_resource_id: str + :keyword private_dns_zone_resource_id: Private DNS zone resource id. + :paramtype private_dns_zone_resource_id: str + """ + super(Network, self).__init__(**kwargs) + self.public_network_access = None + self.delegated_subnet_resource_id = delegated_subnet_resource_id + self.private_dns_zone_resource_id = private_dns_zone_resource_id + + +class Operation(msrest.serialization.Model): + """REST API operation definition. + + :ivar name: The name of the operation being performed on this particular object. + :vartype name: str + :ivar display: The localized display information for this particular operation or action. + :vartype display: ~azure.mgmt.rdbms.mysql_flexibleservers.models.OperationDisplay + :ivar origin: The intended executor of the operation. + :vartype origin: str + :ivar properties: Additional descriptions for the operation. + :vartype properties: dict[str, any] + """ + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'OperationDisplay'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{object}'}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display: Optional["OperationDisplay"] = None, + origin: Optional[str] = None, + properties: Optional[Dict[str, Any]] = None, + **kwargs + ): + """ + :keyword name: The name of the operation being performed on this particular object. + :paramtype name: str + :keyword display: The localized display information for this particular operation or action. + :paramtype display: ~azure.mgmt.rdbms.mysql_flexibleservers.models.OperationDisplay + :keyword origin: The intended executor of the operation. + :paramtype origin: str + :keyword properties: Additional descriptions for the operation. + :paramtype properties: dict[str, any] + """ + super(Operation, self).__init__(**kwargs) + self.name = name + self.display = display + self.origin = origin + self.properties = properties + + +class OperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + :ivar provider: Operation resource provider name. + :vartype provider: str + :ivar resource: Resource on which the operation is performed. + :vartype resource: str + :ivar operation: Localized friendly name for the operation. + :vartype operation: str + :ivar description: Operation description. + :vartype description: str + """ + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: Optional[str] = None, + **kwargs + ): + """ + :keyword provider: Operation resource provider name. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed. + :paramtype resource: str + :keyword operation: Localized friendly name for the operation. + :paramtype operation: str + :keyword description: Operation description. + :paramtype description: str + """ + super(OperationDisplay, self).__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + self.description = description + + +class OperationListResult(msrest.serialization.Model): + """A list of resource provider operations. + + :ivar value: Collection of available operation details. + :vartype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.Operation] + :ivar next_link: URL client should use to fetch the next page (per server side paging). + :vartype next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Operation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["Operation"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: Collection of available operation details. + :paramtype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.Operation] + :keyword next_link: URL client should use to fetch the next page (per server side paging). + :paramtype next_link: str + """ + super(OperationListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar tags: A set of tags. Resource tags. + :vartype tags: dict[str, str] + :ivar location: Required. The geo-location where the resource lives. + :vartype location: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + **kwargs + ): + """ + :keyword tags: A set of tags. Resource tags. + :paramtype tags: dict[str, str] + :keyword location: Required. The geo-location where the resource lives. + :paramtype location: str + """ + super(TrackedResource, self).__init__(**kwargs) + self.tags = tags + self.location = location + + +class Server(TrackedResource): + """Represents a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar tags: A set of tags. Resource tags. + :vartype tags: dict[str, str] + :ivar location: Required. The geo-location where the resource lives. + :vartype location: str + :ivar identity: The cmk identity for the server. + :vartype identity: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Identity + :ivar sku: The SKU (pricing tier) of the server. + :vartype sku: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Sku + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.mysql_flexibleservers.models.SystemData + :ivar administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). + :vartype administrator_login: str + :ivar administrator_login_password: The password of the administrator login (required for + server creation). + :vartype administrator_login_password: str + :ivar version: Server version. Possible values include: "5.7", "8.0.21". + :vartype version: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerVersion + :ivar availability_zone: availability Zone information of the server. + :vartype availability_zone: str + :ivar create_mode: The mode to create a new MySQL server. Possible values include: "Default", + "PointInTimeRestore", "Replica", "GeoRestore". + :vartype create_mode: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.CreateMode + :ivar source_server_resource_id: The source MySQL server id. + :vartype source_server_resource_id: str + :ivar restore_point_in_time: Restore point creation time (ISO8601 format), specifying the time + to restore from. + :vartype restore_point_in_time: ~datetime.datetime + :ivar replication_role: The replication role. Possible values include: "None", "Source", + "Replica". + :vartype replication_role: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.ReplicationRole + :ivar replica_capacity: The maximum number of replicas that a primary server can have. + :vartype replica_capacity: int + :ivar data_encryption: The Data Encryption for CMK. + :vartype data_encryption: ~azure.mgmt.rdbms.mysql_flexibleservers.models.DataEncryption + :ivar state: The state of a server. Possible values include: "Ready", "Dropping", "Disabled", + "Starting", "Stopping", "Stopped", "Updating". + :vartype state: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerState + :ivar fully_qualified_domain_name: The fully qualified domain name of a server. + :vartype fully_qualified_domain_name: str + :ivar storage: Storage related properties of a server. + :vartype storage: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Storage + :ivar backup: Backup related properties of a server. + :vartype backup: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Backup + :ivar high_availability: High availability related properties of a server. + :vartype high_availability: ~azure.mgmt.rdbms.mysql_flexibleservers.models.HighAvailability + :ivar network: Network related properties of a server. + :vartype network: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Network + :ivar maintenance_window: Maintenance window of a server. + :vartype maintenance_window: ~azure.mgmt.rdbms.mysql_flexibleservers.models.MaintenanceWindow + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + 'system_data': {'readonly': True}, + 'replica_capacity': {'readonly': True, 'minimum': 0}, + 'state': {'readonly': True}, + 'fully_qualified_domain_name': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + 'identity': {'key': 'identity', 'type': 'Identity'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'administrator_login': {'key': 'properties.administratorLogin', 'type': 'str'}, + 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'availability_zone': {'key': 'properties.availabilityZone', 'type': 'str'}, + 'create_mode': {'key': 'properties.createMode', 'type': 'str'}, + 'source_server_resource_id': {'key': 'properties.sourceServerResourceId', 'type': 'str'}, + 'restore_point_in_time': {'key': 'properties.restorePointInTime', 'type': 'iso-8601'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + 'replica_capacity': {'key': 'properties.replicaCapacity', 'type': 'int'}, + 'data_encryption': {'key': 'properties.dataEncryption', 'type': 'DataEncryption'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + 'fully_qualified_domain_name': {'key': 'properties.fullyQualifiedDomainName', 'type': 'str'}, + 'storage': {'key': 'properties.storage', 'type': 'Storage'}, + 'backup': {'key': 'properties.backup', 'type': 'Backup'}, + 'high_availability': {'key': 'properties.highAvailability', 'type': 'HighAvailability'}, + 'network': {'key': 'properties.network', 'type': 'Network'}, + 'maintenance_window': {'key': 'properties.maintenanceWindow', 'type': 'MaintenanceWindow'}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + identity: Optional["Identity"] = None, + sku: Optional["Sku"] = None, + administrator_login: Optional[str] = None, + administrator_login_password: Optional[str] = None, + version: Optional[Union[str, "ServerVersion"]] = None, + availability_zone: Optional[str] = None, + create_mode: Optional[Union[str, "CreateMode"]] = None, + source_server_resource_id: Optional[str] = None, + restore_point_in_time: Optional[datetime.datetime] = None, + replication_role: Optional[Union[str, "ReplicationRole"]] = None, + data_encryption: Optional["DataEncryption"] = None, + storage: Optional["Storage"] = None, + backup: Optional["Backup"] = None, + high_availability: Optional["HighAvailability"] = None, + network: Optional["Network"] = None, + maintenance_window: Optional["MaintenanceWindow"] = None, + **kwargs + ): + """ + :keyword tags: A set of tags. Resource tags. + :paramtype tags: dict[str, str] + :keyword location: Required. The geo-location where the resource lives. + :paramtype location: str + :keyword identity: The cmk identity for the server. + :paramtype identity: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Identity + :keyword sku: The SKU (pricing tier) of the server. + :paramtype sku: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Sku + :keyword administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). + :paramtype administrator_login: str + :keyword administrator_login_password: The password of the administrator login (required for + server creation). + :paramtype administrator_login_password: str + :keyword version: Server version. Possible values include: "5.7", "8.0.21". + :paramtype version: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerVersion + :keyword availability_zone: availability Zone information of the server. + :paramtype availability_zone: str + :keyword create_mode: The mode to create a new MySQL server. Possible values include: + "Default", "PointInTimeRestore", "Replica", "GeoRestore". + :paramtype create_mode: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.CreateMode + :keyword source_server_resource_id: The source MySQL server id. + :paramtype source_server_resource_id: str + :keyword restore_point_in_time: Restore point creation time (ISO8601 format), specifying the + time to restore from. + :paramtype restore_point_in_time: ~datetime.datetime + :keyword replication_role: The replication role. Possible values include: "None", "Source", + "Replica". + :paramtype replication_role: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.ReplicationRole + :keyword data_encryption: The Data Encryption for CMK. + :paramtype data_encryption: ~azure.mgmt.rdbms.mysql_flexibleservers.models.DataEncryption + :keyword storage: Storage related properties of a server. + :paramtype storage: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Storage + :keyword backup: Backup related properties of a server. + :paramtype backup: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Backup + :keyword high_availability: High availability related properties of a server. + :paramtype high_availability: ~azure.mgmt.rdbms.mysql_flexibleservers.models.HighAvailability + :keyword network: Network related properties of a server. + :paramtype network: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Network + :keyword maintenance_window: Maintenance window of a server. + :paramtype maintenance_window: ~azure.mgmt.rdbms.mysql_flexibleservers.models.MaintenanceWindow + """ + super(Server, self).__init__(tags=tags, location=location, **kwargs) + self.identity = identity + self.sku = sku + self.system_data = None + self.administrator_login = administrator_login + self.administrator_login_password = administrator_login_password + self.version = version + self.availability_zone = availability_zone + self.create_mode = create_mode + self.source_server_resource_id = source_server_resource_id + self.restore_point_in_time = restore_point_in_time + self.replication_role = replication_role + self.replica_capacity = None + self.data_encryption = data_encryption + self.state = None + self.fully_qualified_domain_name = None + self.storage = storage + self.backup = backup + self.high_availability = high_availability + self.network = network + self.maintenance_window = maintenance_window + + +class ServerBackup(ProxyResource): + """Server backup properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.mysql_flexibleservers.models.SystemData + :ivar backup_type: Backup type. + :vartype backup_type: str + :ivar completed_time: Backup completed time (ISO8601 format). + :vartype completed_time: ~datetime.datetime + :ivar source: Backup source. + :vartype source: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'backup_type': {'key': 'properties.backupType', 'type': 'str'}, + 'completed_time': {'key': 'properties.completedTime', 'type': 'iso-8601'}, + 'source': {'key': 'properties.source', 'type': 'str'}, + } + + def __init__( + self, + *, + backup_type: Optional[str] = None, + completed_time: Optional[datetime.datetime] = None, + source: Optional[str] = None, + **kwargs + ): + """ + :keyword backup_type: Backup type. + :paramtype backup_type: str + :keyword completed_time: Backup completed time (ISO8601 format). + :paramtype completed_time: ~datetime.datetime + :keyword source: Backup source. + :paramtype source: str + """ + super(ServerBackup, self).__init__(**kwargs) + self.system_data = None + self.backup_type = backup_type + self.completed_time = completed_time + self.source = source + + +class ServerBackupListResult(msrest.serialization.Model): + """A list of server backups. + + :ivar value: The list of backups of a server. + :vartype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackup] + :ivar next_link: The link used to get the next page of operations. + :vartype next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerBackup]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["ServerBackup"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: The list of backups of a server. + :paramtype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackup] + :keyword next_link: The link used to get the next page of operations. + :paramtype next_link: str + """ + super(ServerBackupListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ServerEditionCapability(msrest.serialization.Model): + """Server edition capabilities. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: Server edition name. + :vartype name: str + :ivar supported_storage_editions: A list of supported storage editions. + :vartype supported_storage_editions: + list[~azure.mgmt.rdbms.mysql_flexibleservers.models.StorageEditionCapability] + :ivar supported_server_versions: A list of supported server versions. + :vartype supported_server_versions: + list[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerVersionCapability] + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_storage_editions': {'readonly': True}, + 'supported_server_versions': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_storage_editions': {'key': 'supportedStorageEditions', 'type': '[StorageEditionCapability]'}, + 'supported_server_versions': {'key': 'supportedServerVersions', 'type': '[ServerVersionCapability]'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(ServerEditionCapability, self).__init__(**kwargs) + self.name = None + self.supported_storage_editions = None + self.supported_server_versions = None + + +class ServerForUpdate(msrest.serialization.Model): + """Parameters allowed to update for a server. + + :ivar identity: The cmk identity for the server. + :vartype identity: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Identity + :ivar sku: The SKU (pricing tier) of the server. + :vartype sku: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Sku + :ivar tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :vartype tags: dict[str, str] + :ivar administrator_login_password: The password of the administrator login. + :vartype administrator_login_password: str + :ivar storage: Storage related properties of a server. + :vartype storage: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Storage + :ivar backup: Backup related properties of a server. + :vartype backup: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Backup + :ivar high_availability: High availability related properties of a server. + :vartype high_availability: ~azure.mgmt.rdbms.mysql_flexibleservers.models.HighAvailability + :ivar maintenance_window: Maintenance window of a server. + :vartype maintenance_window: ~azure.mgmt.rdbms.mysql_flexibleservers.models.MaintenanceWindow + :ivar replication_role: The replication role of the server. Possible values include: "None", + "Source", "Replica". + :vartype replication_role: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.ReplicationRole + :ivar data_encryption: The Data Encryption for CMK. + :vartype data_encryption: ~azure.mgmt.rdbms.mysql_flexibleservers.models.DataEncryption + """ + + _attribute_map = { + 'identity': {'key': 'identity', 'type': 'Identity'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, + 'storage': {'key': 'properties.storage', 'type': 'Storage'}, + 'backup': {'key': 'properties.backup', 'type': 'Backup'}, + 'high_availability': {'key': 'properties.highAvailability', 'type': 'HighAvailability'}, + 'maintenance_window': {'key': 'properties.maintenanceWindow', 'type': 'MaintenanceWindow'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + 'data_encryption': {'key': 'properties.dataEncryption', 'type': 'DataEncryption'}, + } + + def __init__( + self, + *, + identity: Optional["Identity"] = None, + sku: Optional["Sku"] = None, + tags: Optional[Dict[str, str]] = None, + administrator_login_password: Optional[str] = None, + storage: Optional["Storage"] = None, + backup: Optional["Backup"] = None, + high_availability: Optional["HighAvailability"] = None, + maintenance_window: Optional["MaintenanceWindow"] = None, + replication_role: Optional[Union[str, "ReplicationRole"]] = None, + data_encryption: Optional["DataEncryption"] = None, + **kwargs + ): + """ + :keyword identity: The cmk identity for the server. + :paramtype identity: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Identity + :keyword sku: The SKU (pricing tier) of the server. + :paramtype sku: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Sku + :keyword tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :paramtype tags: dict[str, str] + :keyword administrator_login_password: The password of the administrator login. + :paramtype administrator_login_password: str + :keyword storage: Storage related properties of a server. + :paramtype storage: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Storage + :keyword backup: Backup related properties of a server. + :paramtype backup: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Backup + :keyword high_availability: High availability related properties of a server. + :paramtype high_availability: ~azure.mgmt.rdbms.mysql_flexibleservers.models.HighAvailability + :keyword maintenance_window: Maintenance window of a server. + :paramtype maintenance_window: ~azure.mgmt.rdbms.mysql_flexibleservers.models.MaintenanceWindow + :keyword replication_role: The replication role of the server. Possible values include: "None", + "Source", "Replica". + :paramtype replication_role: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.ReplicationRole + :keyword data_encryption: The Data Encryption for CMK. + :paramtype data_encryption: ~azure.mgmt.rdbms.mysql_flexibleservers.models.DataEncryption + """ + super(ServerForUpdate, self).__init__(**kwargs) + self.identity = identity + self.sku = sku + self.tags = tags + self.administrator_login_password = administrator_login_password + self.storage = storage + self.backup = backup + self.high_availability = high_availability + self.maintenance_window = maintenance_window + self.replication_role = replication_role + self.data_encryption = data_encryption + + +class ServerListResult(msrest.serialization.Model): + """A list of servers. + + :ivar value: The list of servers. + :vartype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :ivar next_link: The link used to get the next page of operations. + :vartype next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Server]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["Server"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: The list of servers. + :paramtype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :keyword next_link: The link used to get the next page of operations. + :paramtype next_link: str + """ + super(ServerListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ServerRestartParameter(msrest.serialization.Model): + """Server restart parameters. + + :ivar restart_with_failover: Whether or not failover to standby server when restarting a server + with high availability enabled. Possible values include: "Enabled", "Disabled". + :vartype restart_with_failover: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum + :ivar max_failover_seconds: The maximum allowed failover time in seconds. + :vartype max_failover_seconds: int + """ + + _attribute_map = { + 'restart_with_failover': {'key': 'restartWithFailover', 'type': 'str'}, + 'max_failover_seconds': {'key': 'maxFailoverSeconds', 'type': 'int'}, + } + + def __init__( + self, + *, + restart_with_failover: Optional[Union[str, "EnableStatusEnum"]] = None, + max_failover_seconds: Optional[int] = None, + **kwargs + ): + """ + :keyword restart_with_failover: Whether or not failover to standby server when restarting a + server with high availability enabled. Possible values include: "Enabled", "Disabled". + :paramtype restart_with_failover: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum + :keyword max_failover_seconds: The maximum allowed failover time in seconds. + :paramtype max_failover_seconds: int + """ + super(ServerRestartParameter, self).__init__(**kwargs) + self.restart_with_failover = restart_with_failover + self.max_failover_seconds = max_failover_seconds + + +class ServerVersionCapability(msrest.serialization.Model): + """Server version capabilities. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: server version. + :vartype name: str + :ivar supported_skus: A list of supported Skus. + :vartype supported_skus: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.SkuCapability] + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_skus': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_skus': {'key': 'supportedSkus', 'type': '[SkuCapability]'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(ServerVersionCapability, self).__init__(**kwargs) + self.name = None + self.supported_skus = None + + +class Sku(msrest.serialization.Model): + """Billing information related properties of a server. + + All required parameters must be populated in order to send to Azure. + + :ivar name: Required. The name of the sku, e.g. Standard_D32s_v3. + :vartype name: str + :ivar tier: Required. The tier of the particular SKU, e.g. GeneralPurpose. Possible values + include: "Burstable", "GeneralPurpose", "MemoryOptimized". + :vartype tier: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.SkuTier + """ + + _validation = { + 'name': {'required': True}, + 'tier': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'tier': {'key': 'tier', 'type': 'str'}, + } + + def __init__( + self, + *, + name: str, + tier: Union[str, "SkuTier"], + **kwargs + ): + """ + :keyword name: Required. The name of the sku, e.g. Standard_D32s_v3. + :paramtype name: str + :keyword tier: Required. The tier of the particular SKU, e.g. GeneralPurpose. Possible values + include: "Burstable", "GeneralPurpose", "MemoryOptimized". + :paramtype tier: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.SkuTier + """ + super(Sku, self).__init__(**kwargs) + self.name = name + self.tier = tier + + +class SkuCapability(msrest.serialization.Model): + """Sku capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: vCore name. + :vartype name: str + :ivar v_cores: supported vCores. + :vartype v_cores: long + :ivar supported_iops: supported IOPS. + :vartype supported_iops: long + :ivar supported_memory_per_v_core_mb: supported memory per vCore in MB. + :vartype supported_memory_per_v_core_mb: long + """ + + _validation = { + 'name': {'readonly': True}, + 'v_cores': {'readonly': True}, + 'supported_iops': {'readonly': True}, + 'supported_memory_per_v_core_mb': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'v_cores': {'key': 'vCores', 'type': 'long'}, + 'supported_iops': {'key': 'supportedIops', 'type': 'long'}, + 'supported_memory_per_v_core_mb': {'key': 'supportedMemoryPerVCoreMB', 'type': 'long'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(SkuCapability, self).__init__(**kwargs) + self.name = None + self.v_cores = None + self.supported_iops = None + self.supported_memory_per_v_core_mb = None + + +class Storage(msrest.serialization.Model): + """Storage Profile properties of a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar storage_size_gb: Max storage size allowed for a server. + :vartype storage_size_gb: int + :ivar iops: Storage IOPS for a server. + :vartype iops: int + :ivar auto_grow: Enable Storage Auto Grow or not. Possible values include: "Enabled", + "Disabled". + :vartype auto_grow: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum + :ivar storage_sku: The sku name of the server storage. + :vartype storage_sku: str + """ + + _validation = { + 'storage_sku': {'readonly': True}, + } + + _attribute_map = { + 'storage_size_gb': {'key': 'storageSizeGB', 'type': 'int'}, + 'iops': {'key': 'iops', 'type': 'int'}, + 'auto_grow': {'key': 'autoGrow', 'type': 'str'}, + 'storage_sku': {'key': 'storageSku', 'type': 'str'}, + } + + def __init__( + self, + *, + storage_size_gb: Optional[int] = None, + iops: Optional[int] = None, + auto_grow: Optional[Union[str, "EnableStatusEnum"]] = None, + **kwargs + ): + """ + :keyword storage_size_gb: Max storage size allowed for a server. + :paramtype storage_size_gb: int + :keyword iops: Storage IOPS for a server. + :paramtype iops: int + :keyword auto_grow: Enable Storage Auto Grow or not. Possible values include: "Enabled", + "Disabled". + :paramtype auto_grow: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum + """ + super(Storage, self).__init__(**kwargs) + self.storage_size_gb = storage_size_gb + self.iops = iops + self.auto_grow = auto_grow + self.storage_sku = None + + +class StorageEditionCapability(msrest.serialization.Model): + """storage edition capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: storage edition name. + :vartype name: str + :ivar min_storage_size: The minimal supported storage size. + :vartype min_storage_size: long + :ivar max_storage_size: The maximum supported storage size. + :vartype max_storage_size: long + :ivar min_backup_retention_days: Minimal backup retention days. + :vartype min_backup_retention_days: long + :ivar max_backup_retention_days: Maximum backup retention days. + :vartype max_backup_retention_days: long + """ + + _validation = { + 'name': {'readonly': True}, + 'min_storage_size': {'readonly': True}, + 'max_storage_size': {'readonly': True}, + 'min_backup_retention_days': {'readonly': True}, + 'max_backup_retention_days': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'min_storage_size': {'key': 'minStorageSize', 'type': 'long'}, + 'max_storage_size': {'key': 'maxStorageSize', 'type': 'long'}, + 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'long'}, + 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'long'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(StorageEditionCapability, self).__init__(**kwargs) + self.name = None + self.min_storage_size = None + self.max_storage_size = None + self.min_backup_retention_days = None + self.max_backup_retention_days = None + + +class SystemData(msrest.serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Possible values include: + "User", "Application", "ManagedIdentity", "Key". + :vartype created_by_type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Possible + values include: "User", "Application", "ManagedIdentity", "Key". + :vartype last_modified_by_type: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + 'created_by': {'key': 'createdBy', 'type': 'str'}, + 'created_by_type': {'key': 'createdByType', 'type': 'str'}, + 'created_at': {'key': 'createdAt', 'type': 'iso-8601'}, + 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'str'}, + 'last_modified_by_type': {'key': 'lastModifiedByType', 'type': 'str'}, + 'last_modified_at': {'key': 'lastModifiedAt', 'type': 'iso-8601'}, + } + + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs + ): + """ + :keyword created_by: The identity that created the resource. + :paramtype created_by: str + :keyword created_by_type: The type of identity that created the resource. Possible values + include: "User", "Application", "ManagedIdentity", "Key". + :paramtype created_by_type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.CreatedByType + :keyword created_at: The timestamp of resource creation (UTC). + :paramtype created_at: ~datetime.datetime + :keyword last_modified_by: The identity that last modified the resource. + :paramtype last_modified_by: str + :keyword last_modified_by_type: The type of identity that last modified the resource. Possible + values include: "User", "Application", "ManagedIdentity", "Key". + :paramtype last_modified_by_type: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.CreatedByType + :keyword last_modified_at: The timestamp of resource last modification (UTC). + :paramtype last_modified_at: ~datetime.datetime + """ + super(SystemData, self).__init__(**kwargs) + self.created_by = created_by + self.created_by_type = created_by_type + self.created_at = created_at + self.last_modified_by = last_modified_by + self.last_modified_by_type = last_modified_by_type + self.last_modified_at = last_modified_at + + +class UserAssignedIdentity(msrest.serialization.Model): + """Metadata of user assigned identity. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: Principal Id of user assigned identity. + :vartype principal_id: str + :ivar client_id: Client Id of user assigned identity. + :vartype client_id: str + """ + + _validation = { + 'principal_id': {'readonly': True}, + 'client_id': {'readonly': True}, + } + + _attribute_map = { + 'principal_id': {'key': 'principalId', 'type': 'str'}, + 'client_id': {'key': 'clientId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(UserAssignedIdentity, self).__init__(**kwargs) + self.principal_id = None + self.client_id = None + + +class VirtualNetworkSubnetUsageParameter(msrest.serialization.Model): + """Virtual network subnet usage parameter. + + :ivar virtual_network_resource_id: Virtual network resource id. + :vartype virtual_network_resource_id: str + """ + + _attribute_map = { + 'virtual_network_resource_id': {'key': 'virtualNetworkResourceId', 'type': 'str'}, + } + + def __init__( + self, + *, + virtual_network_resource_id: Optional[str] = None, + **kwargs + ): + """ + :keyword virtual_network_resource_id: Virtual network resource id. + :paramtype virtual_network_resource_id: str + """ + super(VirtualNetworkSubnetUsageParameter, self).__init__(**kwargs) + self.virtual_network_resource_id = virtual_network_resource_id + + +class VirtualNetworkSubnetUsageResult(msrest.serialization.Model): + """Virtual network subnet usage data. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar delegated_subnets_usage: A list of delegated subnet usage. + :vartype delegated_subnets_usage: + list[~azure.mgmt.rdbms.mysql_flexibleservers.models.DelegatedSubnetUsage] + """ + + _validation = { + 'delegated_subnets_usage': {'readonly': True}, + } + + _attribute_map = { + 'delegated_subnets_usage': {'key': 'delegatedSubnetsUsage', 'type': '[DelegatedSubnetUsage]'}, + } + + def __init__( + self, + **kwargs + ): + """ + """ + super(VirtualNetworkSubnetUsageResult, self).__init__(**kwargs) + self.delegated_subnets_usage = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/models/_my_sql_management_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/models/_my_sql_management_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..e7d0a4835e09abb865f79da49f883febbe1d1a7f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/models/_my_sql_management_client_enums.py @@ -0,0 +1,125 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from six import with_metaclass +from azure.core import CaseInsensitiveEnumMeta + + +class ConfigurationSource(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Source of the configuration. + """ + + SYSTEM_DEFAULT = "system-default" + USER_OVERRIDE = "user-override" + +class CreatedByType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The type of identity that created the resource. + """ + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + +class CreateMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The mode to create a new MySQL server. + """ + + DEFAULT = "Default" + POINT_IN_TIME_RESTORE = "PointInTimeRestore" + REPLICA = "Replica" + GEO_RESTORE = "GeoRestore" + +class DataEncryptionType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The key type, AzureKeyVault for enable cmk, SystemManaged for disable cmk. + """ + + AZURE_KEY_VAULT = "AzureKeyVault" + SYSTEM_MANAGED = "SystemManaged" + +class EnableStatusEnum(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Enum to indicate whether value is 'Enabled' or 'Disabled' + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class HighAvailabilityMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """High availability mode for a server. + """ + + DISABLED = "Disabled" + ZONE_REDUNDANT = "ZoneRedundant" + SAME_ZONE = "SameZone" + +class HighAvailabilityState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The state of server high availability. + """ + + NOT_ENABLED = "NotEnabled" + CREATING_STANDBY = "CreatingStandby" + HEALTHY = "Healthy" + FAILING_OVER = "FailingOver" + REMOVING_STANDBY = "RemovingStandby" + +class IsConfigPendingRestart(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """If is the configuration pending restart or not. + """ + + TRUE = "True" + FALSE = "False" + +class IsDynamicConfig(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """If is the configuration dynamic. + """ + + TRUE = "True" + FALSE = "False" + +class IsReadOnly(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """If is the configuration read only. + """ + + TRUE = "True" + FALSE = "False" + +class ReplicationRole(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The replication role. + """ + + NONE = "None" + SOURCE = "Source" + REPLICA = "Replica" + +class ServerState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The state of a server. + """ + + READY = "Ready" + DROPPING = "Dropping" + DISABLED = "Disabled" + STARTING = "Starting" + STOPPING = "Stopping" + STOPPED = "Stopped" + UPDATING = "Updating" + +class ServerVersion(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The version of a server. + """ + + FIVE7 = "5.7" + EIGHT0_21 = "8.0.21" + +class SkuTier(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """The tier of the particular SKU, e.g. GeneralPurpose. + """ + + BURSTABLE = "Burstable" + GENERAL_PURPOSE = "GeneralPurpose" + MEMORY_OPTIMIZED = "MemoryOptimized" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5d881e8f807c8a3b06636ce6564f65201f4155c6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/__init__.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._servers_operations import ServersOperations +from ._replicas_operations import ReplicasOperations +from ._backups_operations import BackupsOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._databases_operations import DatabasesOperations +from ._configurations_operations import ConfigurationsOperations +from ._location_based_capabilities_operations import LocationBasedCapabilitiesOperations +from ._check_virtual_network_subnet_usage_operations import CheckVirtualNetworkSubnetUsageOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._get_private_dns_zone_suffix_operations import GetPrivateDnsZoneSuffixOperations +from ._operations import Operations + +__all__ = [ + 'ServersOperations', + 'ReplicasOperations', + 'BackupsOperations', + 'FirewallRulesOperations', + 'DatabasesOperations', + 'ConfigurationsOperations', + 'LocationBasedCapabilitiesOperations', + 'CheckVirtualNetworkSubnetUsageOperations', + 'CheckNameAvailabilityOperations', + 'GetPrivateDnsZoneSuffixOperations', + 'Operations', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_backups_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_backups_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5ea5408c363935b344588f66225aa421a3b03f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_backups_operations.py @@ -0,0 +1,250 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + backup_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "backupName": _SERIALIZER.url("backup_name", backup_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class BackupsOperations(object): + """BackupsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + backup_name: str, + **kwargs: Any + ) -> "_models.ServerBackup": + """List all the backups for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param backup_name: The name of the backup. + :type backup_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerBackup, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackup + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerBackup"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + backup_name=backup_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerBackup', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.ServerBackupListResult"]: + """List all the backups for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerBackupListResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackupListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerBackupListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ServerBackupListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_name_availability_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_name_availability_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..985e6e126f03077c7b02f90c38816d7f635e470a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_name_availability_operations.py @@ -0,0 +1,147 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_execute_request( + subscription_id: str, + location_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkNameAvailability') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + +class CheckNameAvailabilityOperations(object): + """CheckNameAvailabilityOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def execute( + self, + location_name: str, + name_availability_request: "_models.NameAvailabilityRequest", + **kwargs: Any + ) -> "_models.NameAvailability": + """Check the availability of name for server. + + :param location_name: The name of the location. + :type location_name: str + :param name_availability_request: The required parameters for checking if server name is + available. + :type name_availability_request: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailabilityRequest + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + + request = build_execute_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + content_type=content_type, + json=_json, + template_url=self.execute.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('NameAvailability', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkNameAvailability'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_virtual_network_subnet_usage_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_virtual_network_subnet_usage_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..40b380fe26c483e613a1b9a43e08c56028d28496 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_virtual_network_subnet_usage_operations.py @@ -0,0 +1,146 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_execute_request( + subscription_id: str, + location_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkVirtualNetworkSubnetUsage') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + +class CheckVirtualNetworkSubnetUsageOperations(object): + """CheckVirtualNetworkSubnetUsageOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def execute( + self, + location_name: str, + parameters: "_models.VirtualNetworkSubnetUsageParameter", + **kwargs: Any + ) -> "_models.VirtualNetworkSubnetUsageResult": + """Get virtual network subnet usage for a given vNet resource id. + + :param location_name: The name of the location. + :type location_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkSubnetUsageResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkSubnetUsageResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'VirtualNetworkSubnetUsageParameter') + + request = build_execute_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + content_type=content_type, + json=_json, + template_url=self.execute.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('VirtualNetworkSubnetUsageResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkVirtualNetworkSubnetUsage'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_configurations_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_configurations_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d3e034cc0ca5d4d728ff8f8ad83123672a21f72b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_configurations_operations.py @@ -0,0 +1,588 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_update_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + configuration_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "configurationName": _SERIALIZER.url("configuration_name", configuration_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PATCH", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + configuration_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "configurationName": _SERIALIZER.url("configuration_name", configuration_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_batch_update_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class ConfigurationsOperations(object): + """ConfigurationsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _update_initial( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> Optional["_models.Configuration"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'Configuration') + + request = build_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + content_type=content_type, + json=_json, + template_url=self._update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> LROPoller["_models.Configuration"]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Configuration or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Configuration', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + **kwargs: Any + ) -> "_models.Configuration": + """Gets information about a configuration of server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Configuration, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + + def _batch_update_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ConfigurationListForBatchUpdate", + **kwargs: Any + ) -> Optional["_models.ConfigurationListResult"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ConfigurationListResult"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ConfigurationListForBatchUpdate') + + request = build_batch_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._batch_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _batch_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations'} # type: ignore + + + @distributed_trace + def begin_batch_update( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ConfigurationListForBatchUpdate", + **kwargs: Any + ) -> LROPoller["_models.ConfigurationListResult"]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The parameters for updating a list of server configuration. + :type parameters: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListForBatchUpdate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ConfigurationListResult or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._batch_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_batch_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations'} # type: ignore + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.ConfigurationListResult"]: + """List all the configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConfigurationListResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_databases_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_databases_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..99203c98609369309fc949c7eee28b424359075b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_databases_operations.py @@ -0,0 +1,563 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_create_or_update_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + database_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_delete_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="DELETE", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class DatabasesOperations(object): + """DatabasesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> Optional["_models.Database"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Database"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'Database') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Database', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> LROPoller["_models.Database"]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Database + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Database or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Database', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace + def begin_delete( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> "_models.Database": + """Gets information about a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Database, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Database + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.DatabaseListResult"]: + """List all the databases in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DatabaseListResult or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.DatabaseListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.DatabaseListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DatabaseListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_firewall_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_firewall_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..217051024ad0f02651204f5ec34f018d7b73eb02 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_firewall_rules_operations.py @@ -0,0 +1,566 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_create_or_update_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_delete_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="DELETE", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class FirewallRulesOperations(object): + """FirewallRulesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> Optional["_models.FirewallRule"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FirewallRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'FirewallRule') + + request = build_create_or_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + content_type=content_type, + json=_json, + template_url=self._create_or_update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> LROPoller["_models.FirewallRule"]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('FirewallRule', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace + def begin_delete( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes a firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> "_models.FirewallRule": + """Gets information about a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FirewallRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.FirewallRuleListResult"]: + """List all the firewall rules in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FirewallRuleListResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("FirewallRuleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..2116d726f5ba7500645b8f48397c732df6966725 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py @@ -0,0 +1,114 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_execute_request( + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/providers/Microsoft.DBforMySQL/getPrivateDnsZoneSuffix') + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class GetPrivateDnsZoneSuffixOperations(object): + """GetPrivateDnsZoneSuffixOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def execute( + self, + **kwargs: Any + ) -> "_models.GetPrivateDnsZoneSuffixResponse": + """Get private DNS zone suffix in the cloud. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GetPrivateDnsZoneSuffixResponse, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.GetPrivateDnsZoneSuffixResponse + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.GetPrivateDnsZoneSuffixResponse"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_execute_request( + template_url=self.execute.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('GetPrivateDnsZoneSuffixResponse', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + execute.metadata = {'url': '/providers/Microsoft.DBforMySQL/getPrivateDnsZoneSuffix'} # type: ignore + diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_location_based_capabilities_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_location_based_capabilities_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0a5e3ae7d16f76ecdcf0ff42e9021636a30f33 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_location_based_capabilities_operations.py @@ -0,0 +1,151 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_request( + subscription_id: str, + location_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/capabilities') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class LocationBasedCapabilitiesOperations(object): + """LocationBasedCapabilitiesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + location_name: str, + **kwargs: Any + ) -> Iterable["_models.CapabilitiesListResult"]: + """Get capabilities at specified location in a given subscription. + + :param location_name: The name of the location. + :type location_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either CapabilitiesListResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.CapabilitiesListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.CapabilitiesListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + location_name=location_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("CapabilitiesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/capabilities'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..0f39251d692dd287a31ccfc10e983a4fac3eeedd --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_operations.py @@ -0,0 +1,135 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_request( + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/providers/Microsoft.DBforMySQL/operations') + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class Operations(object): + """Operations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list( + self, + **kwargs: Any + ) -> Iterable["_models.OperationListResult"]: + """Lists all of the available REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either OperationListResult or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.OperationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.DBforMySQL/operations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_replicas_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_replicas_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..36358b2f80c7df459a555d62c02af5d334adc61d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_replicas_operations.py @@ -0,0 +1,157 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_by_server_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/replicas') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class ReplicasOperations(object): + """ReplicasOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> Iterable["_models.ServerListResult"]: + """List all the replicas for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.list_by_server.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_server_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/replicas'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..90136c9d5ca83a6ed106f1bfb3c4ea6ecc009534 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/mysql_flexibleservers/operations/_servers_operations.py @@ -0,0 +1,1337 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling +from msrest import Serializer + +from .. import models as _models +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_create_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_update_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PATCH", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_delete_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="DELETE", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_get_request( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_by_resource_group_request( + subscription_id: str, + resource_group_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_request( + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/flexibleServers') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_failover_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_restart_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_start_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_stop_request_initial( + subscription_id: str, + resource_group_name: str, + server_name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2021-05-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + +class ServersOperations(object): + """ServersOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.mysql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.Server", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'Server') + + request = build_create_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._create_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + + @distributed_trace + def begin_create( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.Server", + **kwargs: Any + ) -> LROPoller["_models.Server"]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Server + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Server', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + def _update_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForUpdate", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerForUpdate') + + request = build_update_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._update_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForUpdate", + **kwargs: Any + ) -> LROPoller["_models.Server"]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerForUpdate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = self._deserialize('Server', pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_delete_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._delete_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + + @distributed_trace + def begin_delete( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + @distributed_trace + def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.Server": + """Gets information about a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Server, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Server + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_get_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}'} # type: ignore + + + @distributed_trace + def list_by_resource_group( + self, + resource_group_name: str, + **kwargs: Any + ) -> Iterable["_models.ServerListResult"]: + """List all the servers in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + template_url=self.list_by_resource_group.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers'} # type: ignore + + @distributed_trace + def list( + self, + **kwargs: Any + ) -> Iterable["_models.ServerListResult"]: + """List all the servers in a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + + request = build_list_request( + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ServerListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/flexibleServers'} # type: ignore + + def _failover_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_failover_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._failover_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _failover_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover'} # type: ignore + + + @distributed_trace + def begin_failover( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Manual failover a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._failover_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_failover.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover'} # type: ignore + + def _restart_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerRestartParameter", + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(parameters, 'ServerRestartParameter') + + request = build_restart_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + content_type=content_type, + json=_json, + template_url=self._restart_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart'} # type: ignore + + + @distributed_trace + def begin_restart( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerRestartParameter", + **kwargs: Any + ) -> LROPoller[None]: + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for restarting a server. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerRestartParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._restart_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + content_type=content_type, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart'} # type: ignore + + def _start_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_start_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._start_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start'} # type: ignore + + + @distributed_trace + def begin_start( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Starts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._start_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start'} # type: ignore + + def _stop_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + + request = build_stop_request_initial( + subscription_id=self._config.subscription_id, + resource_group_name=resource_group_name, + server_name=server_name, + template_url=self._stop_initial.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _stop_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop'} # type: ignore + + + @distributed_trace + def begin_stop( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Stops a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises: ~azure.core.exceptions.HttpResponseError + """ + polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._stop_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + kwargs.pop('error_map', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + + if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9941983794af3ff6fb87b27113dbff110e321bc9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._postgre_sql_management_client import PostgreSQLManagementClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['PostgreSQLManagementClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..ba1985981030d3fbea9d51be97eeacedbe2417d3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/_configuration.py @@ -0,0 +1,70 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import TokenCredential + + +class PostgreSQLManagementClientConfiguration(Configuration): + """Configuration for PostgreSQLManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(PostgreSQLManagementClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/_postgre_sql_management_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/_postgre_sql_management_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b8b2b4fa450950baa4d7ba5d0b8f04586da98e0d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/_postgre_sql_management_client.py @@ -0,0 +1,174 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.mgmt.core import ARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + + from azure.core.credentials import TokenCredential + from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from ._configuration import PostgreSQLManagementClientConfiguration +from .operations import ServersOperations +from .operations import ReplicasOperations +from .operations import FirewallRulesOperations +from .operations import VirtualNetworkRulesOperations +from .operations import DatabasesOperations +from .operations import ConfigurationsOperations +from .operations import ServerParametersOperations +from .operations import LogFilesOperations +from .operations import ServerAdministratorsOperations +from .operations import RecoverableServersOperations +from .operations import ServerBasedPerformanceTierOperations +from .operations import LocationBasedPerformanceTierOperations +from .operations import CheckNameAvailabilityOperations +from .operations import Operations +from .operations import ServerSecurityAlertPoliciesOperations +from .operations import PrivateEndpointConnectionsOperations +from .operations import PrivateLinkResourcesOperations +from .operations import ServerKeysOperations +from . import models + + +class PostgreSQLManagementClient(object): + """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure PostgreSQL resources including servers, databases, firewall rules, VNET rules, security alert policies, log files and configurations with new business model. + + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.postgresql.operations.ServersOperations + :ivar replicas: ReplicasOperations operations + :vartype replicas: azure.mgmt.rdbms.postgresql.operations.ReplicasOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.rdbms.postgresql.operations.FirewallRulesOperations + :ivar virtual_network_rules: VirtualNetworkRulesOperations operations + :vartype virtual_network_rules: azure.mgmt.rdbms.postgresql.operations.VirtualNetworkRulesOperations + :ivar databases: DatabasesOperations operations + :vartype databases: azure.mgmt.rdbms.postgresql.operations.DatabasesOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: azure.mgmt.rdbms.postgresql.operations.ConfigurationsOperations + :ivar server_parameters: ServerParametersOperations operations + :vartype server_parameters: azure.mgmt.rdbms.postgresql.operations.ServerParametersOperations + :ivar log_files: LogFilesOperations operations + :vartype log_files: azure.mgmt.rdbms.postgresql.operations.LogFilesOperations + :ivar server_administrators: ServerAdministratorsOperations operations + :vartype server_administrators: azure.mgmt.rdbms.postgresql.operations.ServerAdministratorsOperations + :ivar recoverable_servers: RecoverableServersOperations operations + :vartype recoverable_servers: azure.mgmt.rdbms.postgresql.operations.RecoverableServersOperations + :ivar server_based_performance_tier: ServerBasedPerformanceTierOperations operations + :vartype server_based_performance_tier: azure.mgmt.rdbms.postgresql.operations.ServerBasedPerformanceTierOperations + :ivar location_based_performance_tier: LocationBasedPerformanceTierOperations operations + :vartype location_based_performance_tier: azure.mgmt.rdbms.postgresql.operations.LocationBasedPerformanceTierOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: azure.mgmt.rdbms.postgresql.operations.CheckNameAvailabilityOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.postgresql.operations.Operations + :ivar server_security_alert_policies: ServerSecurityAlertPoliciesOperations operations + :vartype server_security_alert_policies: azure.mgmt.rdbms.postgresql.operations.ServerSecurityAlertPoliciesOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: azure.mgmt.rdbms.postgresql.operations.PrivateEndpointConnectionsOperations + :ivar private_link_resources: PrivateLinkResourcesOperations operations + :vartype private_link_resources: azure.mgmt.rdbms.postgresql.operations.PrivateLinkResourcesOperations + :ivar server_keys: ServerKeysOperations operations + :vartype server_keys: azure.mgmt.rdbms.postgresql.operations.ServerKeysOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + base_url=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> None + if not base_url: + base_url = 'https://management.azure.com' + self._config = PostgreSQLManagementClientConfiguration(credential, subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.servers = ServersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations( + self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.virtual_network_rules = VirtualNetworkRulesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_parameters = ServerParametersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.log_files = LogFilesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_administrators = ServerAdministratorsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.recoverable_servers = RecoverableServersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_based_performance_tier = ServerBasedPerformanceTierOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_based_performance_tier = LocationBasedPerformanceTierOperations( + self._client, self._config, self._serialize, self._deserialize) + self.check_name_availability = CheckNameAvailabilityOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + self.server_security_alert_policies = ServerSecurityAlertPoliciesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_keys = ServerKeysOperations( + self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, http_request, **kwargs): + # type: (HttpRequest, Any) -> HttpResponse + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.HttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> PostgreSQLManagementClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..c1257f7f4e111146dae88528000dc4841f2ef2aa --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "10.1.0" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97665f586f8374051945812a833b9b54989f8874 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._postgre_sql_management_client import PostgreSQLManagementClient +__all__ = ['PostgreSQLManagementClient'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff2719be3abab54d5541562cedea3aaa9bb3d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/_configuration.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class PostgreSQLManagementClientConfiguration(Configuration): + """Configuration for PostgreSQLManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(PostgreSQLManagementClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/_postgre_sql_management_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/_postgre_sql_management_client.py new file mode 100644 index 0000000000000000000000000000000000000000..1ef75c65c673a4a3965abe3279a883e5c06456a6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/_postgre_sql_management_client.py @@ -0,0 +1,167 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +from ._configuration import PostgreSQLManagementClientConfiguration +from .operations import ServersOperations +from .operations import ReplicasOperations +from .operations import FirewallRulesOperations +from .operations import VirtualNetworkRulesOperations +from .operations import DatabasesOperations +from .operations import ConfigurationsOperations +from .operations import ServerParametersOperations +from .operations import LogFilesOperations +from .operations import ServerAdministratorsOperations +from .operations import RecoverableServersOperations +from .operations import ServerBasedPerformanceTierOperations +from .operations import LocationBasedPerformanceTierOperations +from .operations import CheckNameAvailabilityOperations +from .operations import Operations +from .operations import ServerSecurityAlertPoliciesOperations +from .operations import PrivateEndpointConnectionsOperations +from .operations import PrivateLinkResourcesOperations +from .operations import ServerKeysOperations +from .. import models + + +class PostgreSQLManagementClient(object): + """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure PostgreSQL resources including servers, databases, firewall rules, VNET rules, security alert policies, log files and configurations with new business model. + + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.postgresql.aio.operations.ServersOperations + :ivar replicas: ReplicasOperations operations + :vartype replicas: azure.mgmt.rdbms.postgresql.aio.operations.ReplicasOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.rdbms.postgresql.aio.operations.FirewallRulesOperations + :ivar virtual_network_rules: VirtualNetworkRulesOperations operations + :vartype virtual_network_rules: azure.mgmt.rdbms.postgresql.aio.operations.VirtualNetworkRulesOperations + :ivar databases: DatabasesOperations operations + :vartype databases: azure.mgmt.rdbms.postgresql.aio.operations.DatabasesOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: azure.mgmt.rdbms.postgresql.aio.operations.ConfigurationsOperations + :ivar server_parameters: ServerParametersOperations operations + :vartype server_parameters: azure.mgmt.rdbms.postgresql.aio.operations.ServerParametersOperations + :ivar log_files: LogFilesOperations operations + :vartype log_files: azure.mgmt.rdbms.postgresql.aio.operations.LogFilesOperations + :ivar server_administrators: ServerAdministratorsOperations operations + :vartype server_administrators: azure.mgmt.rdbms.postgresql.aio.operations.ServerAdministratorsOperations + :ivar recoverable_servers: RecoverableServersOperations operations + :vartype recoverable_servers: azure.mgmt.rdbms.postgresql.aio.operations.RecoverableServersOperations + :ivar server_based_performance_tier: ServerBasedPerformanceTierOperations operations + :vartype server_based_performance_tier: azure.mgmt.rdbms.postgresql.aio.operations.ServerBasedPerformanceTierOperations + :ivar location_based_performance_tier: LocationBasedPerformanceTierOperations operations + :vartype location_based_performance_tier: azure.mgmt.rdbms.postgresql.aio.operations.LocationBasedPerformanceTierOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: azure.mgmt.rdbms.postgresql.aio.operations.CheckNameAvailabilityOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.postgresql.aio.operations.Operations + :ivar server_security_alert_policies: ServerSecurityAlertPoliciesOperations operations + :vartype server_security_alert_policies: azure.mgmt.rdbms.postgresql.aio.operations.ServerSecurityAlertPoliciesOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: azure.mgmt.rdbms.postgresql.aio.operations.PrivateEndpointConnectionsOperations + :ivar private_link_resources: PrivateLinkResourcesOperations operations + :vartype private_link_resources: azure.mgmt.rdbms.postgresql.aio.operations.PrivateLinkResourcesOperations + :ivar server_keys: ServerKeysOperations operations + :vartype server_keys: azure.mgmt.rdbms.postgresql.aio.operations.ServerKeysOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + **kwargs: Any + ) -> None: + if not base_url: + base_url = 'https://management.azure.com' + self._config = PostgreSQLManagementClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.servers = ServersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations( + self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.virtual_network_rules = VirtualNetworkRulesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_parameters = ServerParametersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.log_files = LogFilesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_administrators = ServerAdministratorsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.recoverable_servers = RecoverableServersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_based_performance_tier = ServerBasedPerformanceTierOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_based_performance_tier = LocationBasedPerformanceTierOperations( + self._client, self._config, self._serialize, self._deserialize) + self.check_name_availability = CheckNameAvailabilityOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + self.server_security_alert_policies = ServerSecurityAlertPoliciesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.server_keys = ServerKeysOperations( + self._client, self._config, self._serialize, self._deserialize) + + async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "PostgreSQLManagementClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..170155b069412ade542856e233092d994128b7b8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/__init__.py @@ -0,0 +1,47 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._servers_operations import ServersOperations +from ._replicas_operations import ReplicasOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._virtual_network_rules_operations import VirtualNetworkRulesOperations +from ._databases_operations import DatabasesOperations +from ._configurations_operations import ConfigurationsOperations +from ._server_parameters_operations import ServerParametersOperations +from ._log_files_operations import LogFilesOperations +from ._server_administrators_operations import ServerAdministratorsOperations +from ._recoverable_servers_operations import RecoverableServersOperations +from ._server_based_performance_tier_operations import ServerBasedPerformanceTierOperations +from ._location_based_performance_tier_operations import LocationBasedPerformanceTierOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._operations import Operations +from ._server_security_alert_policies_operations import ServerSecurityAlertPoliciesOperations +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._private_link_resources_operations import PrivateLinkResourcesOperations +from ._server_keys_operations import ServerKeysOperations + +__all__ = [ + 'ServersOperations', + 'ReplicasOperations', + 'FirewallRulesOperations', + 'VirtualNetworkRulesOperations', + 'DatabasesOperations', + 'ConfigurationsOperations', + 'ServerParametersOperations', + 'LogFilesOperations', + 'ServerAdministratorsOperations', + 'RecoverableServersOperations', + 'ServerBasedPerformanceTierOperations', + 'LocationBasedPerformanceTierOperations', + 'CheckNameAvailabilityOperations', + 'Operations', + 'ServerSecurityAlertPoliciesOperations', + 'PrivateEndpointConnectionsOperations', + 'PrivateLinkResourcesOperations', + 'ServerKeysOperations', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_check_name_availability_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_check_name_availability_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..99a1ac2c83f64c9f95522707b1bb73491f27936c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_check_name_availability_operations.py @@ -0,0 +1,100 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class CheckNameAvailabilityOperations: + """CheckNameAvailabilityOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def execute( + self, + name_availability_request: "_models.NameAvailabilityRequest", + **kwargs: Any + ) -> "_models.NameAvailability": + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. + :type name_availability_request: ~azure.mgmt.rdbms.postgresql.models.NameAvailabilityRequest + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.NameAvailability + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.execute.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('NameAvailability', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_configurations_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_configurations_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..af660c9a743bce15049091ea5dd305821ed48b50 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_configurations_operations.py @@ -0,0 +1,313 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ConfigurationsOperations: + """ConfigurationsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> Optional["_models.Configuration"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Configuration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> AsyncLROPoller["_models.Configuration"]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Configuration or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + **kwargs: Any + ) -> "_models.Configuration": + """Gets information about a configuration of server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Configuration, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.Configuration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ConfigurationListResult"]: + """List all the configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConfigurationListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_databases_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_databases_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..faf80e9fd2ce2d2d0c8b90243e9eb7b8048ba107 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_databases_operations.py @@ -0,0 +1,431 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class DatabasesOperations: + """DatabasesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> Optional["_models.Database"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Database"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Database') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Database', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> AsyncLROPoller["_models.Database"]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.Database + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Database or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> "_models.Database": + """Gets information about a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Database, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.Database + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.DatabaseListResult"]: + """List all the databases in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DatabaseListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.DatabaseListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.DatabaseListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('DatabaseListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_firewall_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_firewall_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..991baa7b72cbe7f1b1561e4a58c42199d8fb1fe7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_firewall_rules_operations.py @@ -0,0 +1,431 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class FirewallRulesOperations: + """FirewallRulesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> Optional["_models.FirewallRule"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FirewallRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'FirewallRule') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> AsyncLROPoller["_models.FirewallRule"]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.FirewallRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either FirewallRule or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> "_models.FirewallRule": + """Gets information about a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FirewallRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.FirewallRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.FirewallRuleListResult"]: + """List all the firewall rules in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FirewallRuleListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.FirewallRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('FirewallRuleListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_location_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_location_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..05bc1be6f3703717b59f5a1804b022e883a556a7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_location_based_performance_tier_operations.py @@ -0,0 +1,112 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedPerformanceTierOperations: + """LocationBasedPerformanceTierOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + location_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PerformanceTierListResult"]: + """List all the performance tiers at specified location in a given subscription. + + :param location_name: The name of the location. + :type location_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('PerformanceTierListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_log_files_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_log_files_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b5b44d6b3291700b7b72f208ca4e1e2e305278 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_log_files_operations.py @@ -0,0 +1,116 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LogFilesOperations: + """LogFilesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.LogFileListResult"]: + """List all the log files in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either LogFileListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.LogFileListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.LogFileListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('LogFileListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/logFiles'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1c4586d28214bee3aaf9862a1862c122e5f2c9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_operations.py @@ -0,0 +1,87 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class Operations: + """Operations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def list( + self, + **kwargs: Any + ) -> "_models.OperationListResult": + """Lists all of the available REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationListResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.OperationListResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.list.metadata['url'] # type: ignore + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + list.metadata = {'url': '/providers/Microsoft.DBforPostgreSQL/operations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_private_endpoint_connections_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_private_endpoint_connections_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..6d34c14feaa59cdc8f22e81604e5ac97337f3e26 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_private_endpoint_connections_operations.py @@ -0,0 +1,562 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class PrivateEndpointConnectionsOperations: + """PrivateEndpointConnectionsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> "_models.PrivateEndpointConnection": + """Gets a private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnection + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.PrivateEndpointConnection", + **kwargs: Any + ) -> Optional["_models.PrivateEndpointConnection"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.PrivateEndpointConnection"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'PrivateEndpointConnection') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.PrivateEndpointConnection", + **kwargs: Any + ) -> AsyncLROPoller["_models.PrivateEndpointConnection"]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: + :type parameters: ~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnection + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def _update_tags_initial( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.TagsObject", + **kwargs: Any + ) -> "_models.PrivateEndpointConnection": + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_tags_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'TagsObject') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_tags_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + async def begin_update_tags( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: "_models.TagsObject", + **kwargs: Any + ) -> AsyncLROPoller["_models.PrivateEndpointConnection"]: + """Updates tags on private endpoint connection. + + Updates private endpoint connection with the specified tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: Parameters supplied to the Update private endpoint connection Tags + operation. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.TagsObject + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._update_tags_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PrivateEndpointConnectionListResult"]: + """Gets all private endpoint connections on a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateEndpointConnectionListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnectionListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnectionListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_private_link_resources_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_private_link_resources_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d3581e3e81ff61bda5c286058af0499e07c6dec7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_private_link_resources_operations.py @@ -0,0 +1,178 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class PrivateLinkResourcesOperations: + """PrivateLinkResourcesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PrivateLinkResourceListResult"]: + """Gets the private link resources for PostgreSQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateLinkResourceListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.PrivateLinkResourceListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('PrivateLinkResourceListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateLinkResources'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + group_name: str, + **kwargs: Any + ) -> "_models.PrivateLinkResource": + """Gets a private link resource for PostgreSQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param group_name: The name of the private link resource. + :type group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateLinkResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.PrivateLinkResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'groupName': self._serialize.url("group_name", group_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateLinkResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateLinkResources/{groupName}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_recoverable_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_recoverable_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..c32c126adb3a9775befddfd97d41e88f180d3702 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_recoverable_servers_operations.py @@ -0,0 +1,99 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class RecoverableServersOperations: + """RecoverableServersOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.RecoverableServerResource": + """Gets a recoverable PostgreSQL Server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecoverableServerResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.RecoverableServerResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecoverableServerResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecoverableServerResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/recoverableServers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_replicas_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_replicas_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..331c6831b37497c029bf0810856ac63dffce719a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_replicas_operations.py @@ -0,0 +1,116 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ReplicasOperations: + """ReplicasOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the replicas for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/replicas'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_administrators_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_administrators_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..9202fd8237f1d693182808e44d1e66c0ef3a8aa6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_administrators_operations.py @@ -0,0 +1,414 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerAdministratorsOperations: + """ServerAdministratorsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.ServerAdministratorResource": + """Gets information about a AAD server administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerAdministratorResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.ServerAdministratorResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + properties: "_models.ServerAdministratorResource", + **kwargs: Any + ) -> "_models.ServerAdministratorResource": + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(properties, 'ServerAdministratorResource') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + properties: "_models.ServerAdministratorResource", + **kwargs: Any + ) -> AsyncLROPoller["_models.ServerAdministratorResource"]: + """Creates or update active directory administrator on an existing server. The update action will + overwrite the existing administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param properties: The required parameters for creating or updating an AAD server + administrator. + :type properties: ~azure.mgmt.rdbms.postgresql.models.ServerAdministratorResource + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ServerAdministratorResource or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.ServerAdministratorResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + properties=properties, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes server active directory administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + def list( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerAdministratorResourceListResult"]: + """Returns a list of server Administrators. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerAdministratorResourceListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerAdministratorResourceListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResourceListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerAdministratorResourceListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..4f151593145cc682d9d9aacbf218ac97f680045a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_based_performance_tier_operations.py @@ -0,0 +1,116 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerBasedPerformanceTierOperations: + """ServerBasedPerformanceTierOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.PerformanceTierListResult"]: + """List all the performance tiers for a PostgreSQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('PerformanceTierListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_keys_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_keys_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..194444257432196ea2341488d1090be04fb6f2be --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_keys_operations.py @@ -0,0 +1,430 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerKeysOperations: + """ServerKeysOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerKeyListResult"]: + """Gets a list of Server keys. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerKeyListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerKeyListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKeyListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerKeyListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + key_name: str, + **kwargs: Any + ) -> "_models.ServerKey": + """Gets a PostgreSQL Server key. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the PostgreSQL Server key to be retrieved. + :type key_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerKey, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.ServerKey + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerKey', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + async def _create_or_update_initial( + self, + server_name: str, + key_name: str, + resource_group_name: str, + parameters: "_models.ServerKey", + **kwargs: Any + ) -> "_models.ServerKey": + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerKey') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('ServerKey', pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize('ServerKey', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + async def begin_create_or_update( + self, + server_name: str, + key_name: str, + resource_group_name: str, + parameters: "_models.ServerKey", + **kwargs: Any + ) -> AsyncLROPoller["_models.ServerKey"]: + """Creates or updates a PostgreSQL Server key. + + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the PostgreSQL Server key to be operated on (updated or created). + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param parameters: The requested PostgreSQL Server key resource state. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.ServerKey + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ServerKey or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.ServerKey] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + server_name=server_name, + key_name=key_name, + resource_group_name=resource_group_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ServerKey', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + async def _delete_initial( + self, + server_name: str, + key_name: str, + resource_group_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + async def begin_delete( + self, + server_name: str, + key_name: str, + resource_group_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the PostgreSQL Server key with the given name. + + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the PostgreSQL Server key to be deleted. + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + server_name=server_name, + key_name=key_name, + resource_group_name=resource_group_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_parameters_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_parameters_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..627e1e6050f7ddde3307715b5c765674ea63fe2d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_parameters_operations.py @@ -0,0 +1,169 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerParametersOperations: + """ServerParametersOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _list_update_configurations_initial( + self, + resource_group_name: str, + server_name: str, + value: "_models.ConfigurationListResult", + **kwargs: Any + ) -> Optional["_models.ConfigurationListResult"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ConfigurationListResult"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._list_update_configurations_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(value, 'ConfigurationListResult') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _list_update_configurations_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/updateConfigurations'} # type: ignore + + async def begin_list_update_configurations( + self, + resource_group_name: str, + server_name: str, + value: "_models.ConfigurationListResult", + **kwargs: Any + ) -> AsyncLROPoller["_models.ConfigurationListResult"]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param value: The parameters for updating a list of server configuration. + :type value: ~azure.mgmt.rdbms.postgresql.models.ConfigurationListResult + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ConfigurationListResult or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._list_update_configurations_initial( + resource_group_name=resource_group_name, + server_name=server_name, + value=value, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_list_update_configurations.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/updateConfigurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_security_alert_policies_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_security_alert_policies_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b65aef73426324f33b56a8fb339c18bedcb904a2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_server_security_alert_policies_operations.py @@ -0,0 +1,313 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServerSecurityAlertPoliciesOperations: + """ServerSecurityAlertPoliciesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + **kwargs: Any + ) -> "_models.ServerSecurityAlertPolicy": + """Get a server's security alert policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the security alert policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.postgresql.models.SecurityAlertPolicyName + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerSecurityAlertPolicy, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicy + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + parameters: "_models.ServerSecurityAlertPolicy", + **kwargs: Any + ) -> Optional["_models.ServerSecurityAlertPolicy"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ServerSecurityAlertPolicy"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerSecurityAlertPolicy') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + parameters: "_models.ServerSecurityAlertPolicy", + **kwargs: Any + ) -> AsyncLROPoller["_models.ServerSecurityAlertPolicy"]: + """Creates or updates a threat detection policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the threat detection policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.postgresql.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicy + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ServerSecurityAlertPolicy or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + security_alert_policy_name=security_alert_policy_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerSecurityAlertPolicyListResult"]: + """Get the server's threat detection policies. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerSecurityAlertPolicyListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicyListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicyListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerSecurityAlertPolicyListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..472faa41f4cff36ca65a3839edc78be951837ba5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_servers_operations.py @@ -0,0 +1,710 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServersOperations: + """ServersOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForCreate", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerForCreate') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + async def begin_create( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForCreate", + **kwargs: Any + ) -> AsyncLROPoller["_models.Server"]: + """Creates a new server, or will overwrite an existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.ServerForCreate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + async def _update_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpdateParameters", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerUpdateParameters') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + async def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerUpdateParameters", + **kwargs: Any + ) -> AsyncLROPoller["_models.Server"]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.ServerUpdateParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.Server": + """Gets information about a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Server, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.Server + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + def list_by_resource_group( + self, + resource_group_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the servers in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_resource_group.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers'} # type: ignore + + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the servers in a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/servers'} # type: ignore + + async def _restart_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self._restart_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/restart'} # type: ignore + + async def begin_restart( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._restart_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/restart'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_virtual_network_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_virtual_network_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..260b371fc26c634d59939fc9341bebc7095ce859 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/aio/operations/_virtual_network_rules_operations.py @@ -0,0 +1,429 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class VirtualNetworkRulesOperations: + """VirtualNetworkRulesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> "_models.VirtualNetworkRule": + """Gets a virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: "_models.VirtualNetworkRule", + **kwargs: Any + ) -> Optional["_models.VirtualNetworkRule"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.VirtualNetworkRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'VirtualNetworkRule') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: "_models.VirtualNetworkRule", + **kwargs: Any + ) -> AsyncLROPoller["_models.VirtualNetworkRule"]: + """Creates or updates an existing virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :param parameters: The requested virtual Network Rule Resource state. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either VirtualNetworkRule or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the virtual network rule with the given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.VirtualNetworkRuleListResult"]: + """Gets a list of virtual network rules in a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either VirtualNetworkRuleListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('VirtualNetworkRuleListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6700f031d93dcf14763658c9f776669bc1a3c092 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/__init__.py @@ -0,0 +1,213 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import Configuration + from ._models_py3 import ConfigurationListResult + from ._models_py3 import Database + from ._models_py3 import DatabaseListResult + from ._models_py3 import ErrorAdditionalInfo + from ._models_py3 import ErrorResponse + from ._models_py3 import FirewallRule + from ._models_py3 import FirewallRuleListResult + from ._models_py3 import LogFile + from ._models_py3 import LogFileListResult + from ._models_py3 import NameAvailability + from ._models_py3 import NameAvailabilityRequest + from ._models_py3 import Operation + from ._models_py3 import OperationDisplay + from ._models_py3 import OperationListResult + from ._models_py3 import PerformanceTierListResult + from ._models_py3 import PerformanceTierProperties + from ._models_py3 import PerformanceTierServiceLevelObjectives + from ._models_py3 import PrivateEndpointConnection + from ._models_py3 import PrivateEndpointConnectionListResult + from ._models_py3 import PrivateEndpointProperty + from ._models_py3 import PrivateLinkResource + from ._models_py3 import PrivateLinkResourceListResult + from ._models_py3 import PrivateLinkResourceProperties + from ._models_py3 import PrivateLinkServiceConnectionStateProperty + from ._models_py3 import ProxyResource + from ._models_py3 import RecoverableServerResource + from ._models_py3 import Resource + from ._models_py3 import ResourceIdentity + from ._models_py3 import Server + from ._models_py3 import ServerAdministratorResource + from ._models_py3 import ServerAdministratorResourceListResult + from ._models_py3 import ServerForCreate + from ._models_py3 import ServerKey + from ._models_py3 import ServerKeyListResult + from ._models_py3 import ServerListResult + from ._models_py3 import ServerPrivateEndpointConnection + from ._models_py3 import ServerPrivateEndpointConnectionProperties + from ._models_py3 import ServerPrivateLinkServiceConnectionStateProperty + from ._models_py3 import ServerPropertiesForCreate + from ._models_py3 import ServerPropertiesForDefaultCreate + from ._models_py3 import ServerPropertiesForGeoRestore + from ._models_py3 import ServerPropertiesForReplica + from ._models_py3 import ServerPropertiesForRestore + from ._models_py3 import ServerSecurityAlertPolicy + from ._models_py3 import ServerSecurityAlertPolicyListResult + from ._models_py3 import ServerUpdateParameters + from ._models_py3 import Sku + from ._models_py3 import StorageProfile + from ._models_py3 import TagsObject + from ._models_py3 import TrackedResource + from ._models_py3 import VirtualNetworkRule + from ._models_py3 import VirtualNetworkRuleListResult +except (SyntaxError, ImportError): + from ._models import Configuration # type: ignore + from ._models import ConfigurationListResult # type: ignore + from ._models import Database # type: ignore + from ._models import DatabaseListResult # type: ignore + from ._models import ErrorAdditionalInfo # type: ignore + from ._models import ErrorResponse # type: ignore + from ._models import FirewallRule # type: ignore + from ._models import FirewallRuleListResult # type: ignore + from ._models import LogFile # type: ignore + from ._models import LogFileListResult # type: ignore + from ._models import NameAvailability # type: ignore + from ._models import NameAvailabilityRequest # type: ignore + from ._models import Operation # type: ignore + from ._models import OperationDisplay # type: ignore + from ._models import OperationListResult # type: ignore + from ._models import PerformanceTierListResult # type: ignore + from ._models import PerformanceTierProperties # type: ignore + from ._models import PerformanceTierServiceLevelObjectives # type: ignore + from ._models import PrivateEndpointConnection # type: ignore + from ._models import PrivateEndpointConnectionListResult # type: ignore + from ._models import PrivateEndpointProperty # type: ignore + from ._models import PrivateLinkResource # type: ignore + from ._models import PrivateLinkResourceListResult # type: ignore + from ._models import PrivateLinkResourceProperties # type: ignore + from ._models import PrivateLinkServiceConnectionStateProperty # type: ignore + from ._models import ProxyResource # type: ignore + from ._models import RecoverableServerResource # type: ignore + from ._models import Resource # type: ignore + from ._models import ResourceIdentity # type: ignore + from ._models import Server # type: ignore + from ._models import ServerAdministratorResource # type: ignore + from ._models import ServerAdministratorResourceListResult # type: ignore + from ._models import ServerForCreate # type: ignore + from ._models import ServerKey # type: ignore + from ._models import ServerKeyListResult # type: ignore + from ._models import ServerListResult # type: ignore + from ._models import ServerPrivateEndpointConnection # type: ignore + from ._models import ServerPrivateEndpointConnectionProperties # type: ignore + from ._models import ServerPrivateLinkServiceConnectionStateProperty # type: ignore + from ._models import ServerPropertiesForCreate # type: ignore + from ._models import ServerPropertiesForDefaultCreate # type: ignore + from ._models import ServerPropertiesForGeoRestore # type: ignore + from ._models import ServerPropertiesForReplica # type: ignore + from ._models import ServerPropertiesForRestore # type: ignore + from ._models import ServerSecurityAlertPolicy # type: ignore + from ._models import ServerSecurityAlertPolicyListResult # type: ignore + from ._models import ServerUpdateParameters # type: ignore + from ._models import Sku # type: ignore + from ._models import StorageProfile # type: ignore + from ._models import TagsObject # type: ignore + from ._models import TrackedResource # type: ignore + from ._models import VirtualNetworkRule # type: ignore + from ._models import VirtualNetworkRuleListResult # type: ignore + +from ._postgre_sql_management_client_enums import ( + CreateMode, + GeoRedundantBackup, + IdentityType, + InfrastructureEncryption, + MinimalTlsVersionEnum, + OperationOrigin, + PrivateEndpointProvisioningState, + PrivateLinkServiceConnectionStateActionsRequire, + PrivateLinkServiceConnectionStateStatus, + PublicNetworkAccessEnum, + SecurityAlertPolicyName, + ServerKeyType, + ServerSecurityAlertPolicyState, + ServerState, + ServerVersion, + SkuTier, + SslEnforcementEnum, + StorageAutogrow, + VirtualNetworkRuleState, +) + +__all__ = [ + 'Configuration', + 'ConfigurationListResult', + 'Database', + 'DatabaseListResult', + 'ErrorAdditionalInfo', + 'ErrorResponse', + 'FirewallRule', + 'FirewallRuleListResult', + 'LogFile', + 'LogFileListResult', + 'NameAvailability', + 'NameAvailabilityRequest', + 'Operation', + 'OperationDisplay', + 'OperationListResult', + 'PerformanceTierListResult', + 'PerformanceTierProperties', + 'PerformanceTierServiceLevelObjectives', + 'PrivateEndpointConnection', + 'PrivateEndpointConnectionListResult', + 'PrivateEndpointProperty', + 'PrivateLinkResource', + 'PrivateLinkResourceListResult', + 'PrivateLinkResourceProperties', + 'PrivateLinkServiceConnectionStateProperty', + 'ProxyResource', + 'RecoverableServerResource', + 'Resource', + 'ResourceIdentity', + 'Server', + 'ServerAdministratorResource', + 'ServerAdministratorResourceListResult', + 'ServerForCreate', + 'ServerKey', + 'ServerKeyListResult', + 'ServerListResult', + 'ServerPrivateEndpointConnection', + 'ServerPrivateEndpointConnectionProperties', + 'ServerPrivateLinkServiceConnectionStateProperty', + 'ServerPropertiesForCreate', + 'ServerPropertiesForDefaultCreate', + 'ServerPropertiesForGeoRestore', + 'ServerPropertiesForReplica', + 'ServerPropertiesForRestore', + 'ServerSecurityAlertPolicy', + 'ServerSecurityAlertPolicyListResult', + 'ServerUpdateParameters', + 'Sku', + 'StorageProfile', + 'TagsObject', + 'TrackedResource', + 'VirtualNetworkRule', + 'VirtualNetworkRuleListResult', + 'CreateMode', + 'GeoRedundantBackup', + 'IdentityType', + 'InfrastructureEncryption', + 'MinimalTlsVersionEnum', + 'OperationOrigin', + 'PrivateEndpointProvisioningState', + 'PrivateLinkServiceConnectionStateActionsRequire', + 'PrivateLinkServiceConnectionStateStatus', + 'PublicNetworkAccessEnum', + 'SecurityAlertPolicyName', + 'ServerKeyType', + 'ServerSecurityAlertPolicyState', + 'ServerState', + 'ServerVersion', + 'SkuTier', + 'SslEnforcementEnum', + 'StorageAutogrow', + 'VirtualNetworkRuleState', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/_models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..c158141235481e144b0aaba95b2e3d9653f852aa --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/_models.py @@ -0,0 +1,2172 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import msrest.serialization + + +class Resource(msrest.serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class Configuration(ProxyResource): + """Represents a Configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param value: Value of the configuration. + :type value: str + :ivar description: Description of the configuration. + :vartype description: str + :ivar default_value: Default value of the configuration. + :vartype default_value: str + :ivar data_type: Data type of the configuration. + :vartype data_type: str + :ivar allowed_values: Allowed values of the configuration. + :vartype allowed_values: str + :param source: Source of the configuration. + :type source: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'description': {'readonly': True}, + 'default_value': {'readonly': True}, + 'data_type': {'readonly': True}, + 'allowed_values': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'value': {'key': 'properties.value', 'type': 'str'}, + 'description': {'key': 'properties.description', 'type': 'str'}, + 'default_value': {'key': 'properties.defaultValue', 'type': 'str'}, + 'data_type': {'key': 'properties.dataType', 'type': 'str'}, + 'allowed_values': {'key': 'properties.allowedValues', 'type': 'str'}, + 'source': {'key': 'properties.source', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Configuration, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.description = None + self.default_value = None + self.data_type = None + self.allowed_values = None + self.source = kwargs.get('source', None) + + +class ConfigurationListResult(msrest.serialization.Model): + """A list of server configurations. + + :param value: The list of server configurations. + :type value: list[~azure.mgmt.rdbms.postgresql.models.Configuration] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Configuration]'}, + } + + def __init__( + self, + **kwargs + ): + super(ConfigurationListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class Database(ProxyResource): + """Represents a Database. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param charset: The charset of the database. + :type charset: str + :param collation: The collation of the database. + :type collation: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'charset': {'key': 'properties.charset', 'type': 'str'}, + 'collation': {'key': 'properties.collation', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Database, self).__init__(**kwargs) + self.charset = kwargs.get('charset', None) + self.collation = kwargs.get('collation', None) + + +class DatabaseListResult(msrest.serialization.Model): + """A List of databases. + + :param value: The list of databases housed in a server. + :type value: list[~azure.mgmt.rdbms.postgresql.models.Database] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Database]'}, + } + + def __init__( + self, + **kwargs + ): + super(DatabaseListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class ErrorAdditionalInfo(msrest.serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorResponse(msrest.serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.rdbms.postgresql.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.rdbms.postgresql.models.ErrorAdditionalInfo] + """ + + _validation = { + 'code': {'readonly': True}, + 'message': {'readonly': True}, + 'target': {'readonly': True}, + 'details': {'readonly': True}, + 'additional_info': {'readonly': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'target': {'key': 'target', 'type': 'str'}, + 'details': {'key': 'details', 'type': '[ErrorResponse]'}, + 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class FirewallRule(ProxyResource): + """Represents a server firewall rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param start_ip_address: Required. The start IP address of the server firewall rule. Must be + IPv4 format. + :type start_ip_address: str + :param end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 + format. + :type end_ip_address: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'start_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + 'end_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'start_ip_address': {'key': 'properties.startIpAddress', 'type': 'str'}, + 'end_ip_address': {'key': 'properties.endIpAddress', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FirewallRule, self).__init__(**kwargs) + self.start_ip_address = kwargs['start_ip_address'] + self.end_ip_address = kwargs['end_ip_address'] + + +class FirewallRuleListResult(msrest.serialization.Model): + """A list of firewall rules. + + :param value: The list of firewall rules in a server. + :type value: list[~azure.mgmt.rdbms.postgresql.models.FirewallRule] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FirewallRule]'}, + } + + def __init__( + self, + **kwargs + ): + super(FirewallRuleListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class LogFile(ProxyResource): + """Represents a log file. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param size_in_kb: Size of the log file. + :type size_in_kb: long + :ivar created_time: Creation timestamp of the log file. + :vartype created_time: ~datetime.datetime + :ivar last_modified_time: Last modified timestamp of the log file. + :vartype last_modified_time: ~datetime.datetime + :param type_properties_type: Type of the log file. + :type type_properties_type: str + :param url: The url to download the log file from. + :type url: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'created_time': {'readonly': True}, + 'last_modified_time': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'size_in_kb': {'key': 'properties.sizeInKB', 'type': 'long'}, + 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, + 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'iso-8601'}, + 'type_properties_type': {'key': 'properties.type', 'type': 'str'}, + 'url': {'key': 'properties.url', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(LogFile, self).__init__(**kwargs) + self.size_in_kb = kwargs.get('size_in_kb', None) + self.created_time = None + self.last_modified_time = None + self.type_properties_type = kwargs.get('type_properties_type', None) + self.url = kwargs.get('url', None) + + +class LogFileListResult(msrest.serialization.Model): + """A list of log files. + + :param value: The list of log files. + :type value: list[~azure.mgmt.rdbms.postgresql.models.LogFile] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[LogFile]'}, + } + + def __init__( + self, + **kwargs + ): + super(LogFileListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class NameAvailability(msrest.serialization.Model): + """Represents a resource name availability. + + :param message: Error Message. + :type message: str + :param name_available: Indicates whether the resource name is available. + :type name_available: bool + :param reason: Reason for name being unavailable. + :type reason: str + """ + + _attribute_map = { + 'message': {'key': 'message', 'type': 'str'}, + 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, + 'reason': {'key': 'reason', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(NameAvailability, self).__init__(**kwargs) + self.message = kwargs.get('message', None) + self.name_available = kwargs.get('name_available', None) + self.reason = kwargs.get('reason', None) + + +class NameAvailabilityRequest(msrest.serialization.Model): + """Request from client to check resource name availability. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. Resource name to verify. + :type name: str + :param type: Resource type used for verification. + :type type: str + """ + + _validation = { + 'name': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(NameAvailabilityRequest, self).__init__(**kwargs) + self.name = kwargs['name'] + self.type = kwargs.get('type', None) + + +class Operation(msrest.serialization.Model): + """REST API operation definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation being performed on this particular object. + :vartype name: str + :ivar display: The localized display information for this particular operation or action. + :vartype display: ~azure.mgmt.rdbms.postgresql.models.OperationDisplay + :ivar origin: The intended executor of the operation. Possible values include: "NotSpecified", + "user", "system". + :vartype origin: str or ~azure.mgmt.rdbms.postgresql.models.OperationOrigin + :ivar properties: Additional descriptions for the operation. + :vartype properties: dict[str, any] + """ + + _validation = { + 'name': {'readonly': True}, + 'display': {'readonly': True}, + 'origin': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'OperationDisplay'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{object}'}, + } + + def __init__( + self, + **kwargs + ): + super(Operation, self).__init__(**kwargs) + self.name = None + self.display = None + self.origin = None + self.properties = None + + +class OperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: Operation resource provider name. + :vartype provider: str + :ivar resource: Resource on which the operation is performed. + :vartype resource: str + :ivar operation: Localized friendly name for the operation. + :vartype operation: str + :ivar description: Operation description. + :vartype description: str + """ + + _validation = { + 'provider': {'readonly': True}, + 'resource': {'readonly': True}, + 'operation': {'readonly': True}, + 'description': {'readonly': True}, + } + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationDisplay, self).__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(msrest.serialization.Model): + """A list of resource provider operations. + + :param value: The list of resource provider operations. + :type value: list[~azure.mgmt.rdbms.postgresql.models.Operation] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Operation]'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class PerformanceTierListResult(msrest.serialization.Model): + """A list of performance tiers. + + :param value: The list of performance tiers. + :type value: list[~azure.mgmt.rdbms.postgresql.models.PerformanceTierProperties] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PerformanceTierProperties]'}, + } + + def __init__( + self, + **kwargs + ): + super(PerformanceTierListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class PerformanceTierProperties(msrest.serialization.Model): + """Performance tier properties. + + :param id: ID of the performance tier. + :type id: str + :param max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :type max_backup_retention_days: int + :param min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :type min_backup_retention_days: int + :param max_storage_mb: Max storage allowed for a server. + :type max_storage_mb: int + :param min_large_storage_mb: Max storage allowed for a server. + :type min_large_storage_mb: int + :param max_large_storage_mb: Max storage allowed for a server. + :type max_large_storage_mb: int + :param min_storage_mb: Max storage allowed for a server. + :type min_storage_mb: int + :param service_level_objectives: Service level objectives associated with the performance tier. + :type service_level_objectives: + list[~azure.mgmt.rdbms.postgresql.models.PerformanceTierServiceLevelObjectives] + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, + 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, + 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, + 'min_large_storage_mb': {'key': 'minLargeStorageMB', 'type': 'int'}, + 'max_large_storage_mb': {'key': 'maxLargeStorageMB', 'type': 'int'}, + 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, + 'service_level_objectives': {'key': 'serviceLevelObjectives', 'type': '[PerformanceTierServiceLevelObjectives]'}, + } + + def __init__( + self, + **kwargs + ): + super(PerformanceTierProperties, self).__init__(**kwargs) + self.id = kwargs.get('id', None) + self.max_backup_retention_days = kwargs.get('max_backup_retention_days', None) + self.min_backup_retention_days = kwargs.get('min_backup_retention_days', None) + self.max_storage_mb = kwargs.get('max_storage_mb', None) + self.min_large_storage_mb = kwargs.get('min_large_storage_mb', None) + self.max_large_storage_mb = kwargs.get('max_large_storage_mb', None) + self.min_storage_mb = kwargs.get('min_storage_mb', None) + self.service_level_objectives = kwargs.get('service_level_objectives', None) + + +class PerformanceTierServiceLevelObjectives(msrest.serialization.Model): + """Service level objectives for performance tier. + + :param id: ID for the service level objective. + :type id: str + :param edition: Edition of the performance tier. + :type edition: str + :param v_core: vCore associated with the service level objective. + :type v_core: int + :param hardware_generation: Hardware generation associated with the service level objective. + :type hardware_generation: str + :param max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :type max_backup_retention_days: int + :param min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :type min_backup_retention_days: int + :param max_storage_mb: Max storage allowed for a server. + :type max_storage_mb: int + :param min_storage_mb: Max storage allowed for a server. + :type min_storage_mb: int + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'edition': {'key': 'edition', 'type': 'str'}, + 'v_core': {'key': 'vCore', 'type': 'int'}, + 'hardware_generation': {'key': 'hardwareGeneration', 'type': 'str'}, + 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, + 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, + 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, + 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, + } + + def __init__( + self, + **kwargs + ): + super(PerformanceTierServiceLevelObjectives, self).__init__(**kwargs) + self.id = kwargs.get('id', None) + self.edition = kwargs.get('edition', None) + self.v_core = kwargs.get('v_core', None) + self.hardware_generation = kwargs.get('hardware_generation', None) + self.max_backup_retention_days = kwargs.get('max_backup_retention_days', None) + self.min_backup_retention_days = kwargs.get('min_backup_retention_days', None) + self.max_storage_mb = kwargs.get('max_storage_mb', None) + self.min_storage_mb = kwargs.get('min_storage_mb', None) + + +class PrivateEndpointConnection(ProxyResource): + """A private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param private_endpoint: Private endpoint which the connection belongs to. + :type private_endpoint: ~azure.mgmt.rdbms.postgresql.models.PrivateEndpointProperty + :param private_link_service_connection_state: Connection state of the private endpoint + connection. + :type private_link_service_connection_state: + ~azure.mgmt.rdbms.postgresql.models.PrivateLinkServiceConnectionStateProperty + :ivar provisioning_state: State of the private endpoint connection. + :vartype provisioning_state: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpointProperty'}, + 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionStateProperty'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateEndpointConnection, self).__init__(**kwargs) + self.private_endpoint = kwargs.get('private_endpoint', None) + self.private_link_service_connection_state = kwargs.get('private_link_service_connection_state', None) + self.provisioning_state = None + + +class PrivateEndpointConnectionListResult(msrest.serialization.Model): + """A list of private endpoint connections. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnection] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PrivateEndpointConnection]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateEndpointConnectionListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class PrivateEndpointProperty(msrest.serialization.Model): + """PrivateEndpointProperty. + + :param id: Resource id of the private endpoint. + :type id: str + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateEndpointProperty, self).__init__(**kwargs) + self.id = kwargs.get('id', None) + + +class PrivateLinkResource(ProxyResource): + """A private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar properties: The private link resource group id. + :vartype properties: ~azure.mgmt.rdbms.postgresql.models.PrivateLinkResourceProperties + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'PrivateLinkResourceProperties'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResource, self).__init__(**kwargs) + self.properties = None + + +class PrivateLinkResourceListResult(msrest.serialization.Model): + """A list of private link resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.postgresql.models.PrivateLinkResource] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PrivateLinkResource]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResourceListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class PrivateLinkResourceProperties(msrest.serialization.Model): + """Properties of a private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar group_id: The private link resource group id. + :vartype group_id: str + :ivar required_members: The private link resource required member names. + :vartype required_members: list[str] + """ + + _validation = { + 'group_id': {'readonly': True}, + 'required_members': {'readonly': True}, + } + + _attribute_map = { + 'group_id': {'key': 'groupId', 'type': 'str'}, + 'required_members': {'key': 'requiredMembers', 'type': '[str]'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResourceProperties, self).__init__(**kwargs) + self.group_id = None + self.required_members = None + + +class PrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): + """PrivateLinkServiceConnectionStateProperty. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param status: Required. The private link service connection status. + :type status: str + :param description: Required. The private link service connection description. + :type description: str + :ivar actions_required: The actions required for private link service connection. + :vartype actions_required: str + """ + + _validation = { + 'status': {'required': True}, + 'description': {'required': True}, + 'actions_required': {'readonly': True}, + } + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + self.status = kwargs['status'] + self.description = kwargs['description'] + self.actions_required = None + + +class RecoverableServerResource(ProxyResource): + """A recoverable server resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar last_available_backup_date_time: The last available backup date time. + :vartype last_available_backup_date_time: str + :ivar service_level_objective: The service level objective. + :vartype service_level_objective: str + :ivar edition: Edition of the performance tier. + :vartype edition: str + :ivar v_core: vCore associated with the service level objective. + :vartype v_core: int + :ivar hardware_generation: Hardware generation associated with the service level objective. + :vartype hardware_generation: str + :ivar version: The PostgreSQL version. + :vartype version: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'last_available_backup_date_time': {'readonly': True}, + 'service_level_objective': {'readonly': True}, + 'edition': {'readonly': True}, + 'v_core': {'readonly': True}, + 'hardware_generation': {'readonly': True}, + 'version': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'last_available_backup_date_time': {'key': 'properties.lastAvailableBackupDateTime', 'type': 'str'}, + 'service_level_objective': {'key': 'properties.serviceLevelObjective', 'type': 'str'}, + 'edition': {'key': 'properties.edition', 'type': 'str'}, + 'v_core': {'key': 'properties.vCore', 'type': 'int'}, + 'hardware_generation': {'key': 'properties.hardwareGeneration', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RecoverableServerResource, self).__init__(**kwargs) + self.last_available_backup_date_time = None + self.service_level_objective = None + self.edition = None + self.v_core = None + self.hardware_generation = None + self.version = None + + +class ResourceIdentity(msrest.serialization.Model): + """Azure Active Directory identity configuration for a resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The Azure Active Directory principal id. + :vartype principal_id: str + :param type: The identity type. Set this to 'SystemAssigned' in order to automatically create + and assign an Azure Active Directory principal for the resource. Possible values include: + "SystemAssigned". + :type type: str or ~azure.mgmt.rdbms.postgresql.models.IdentityType + :ivar tenant_id: The Azure Active Directory tenant id. + :vartype tenant_id: str + """ + + _validation = { + 'principal_id': {'readonly': True}, + 'tenant_id': {'readonly': True}, + } + + _attribute_map = { + 'principal_id': {'key': 'principalId', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tenant_id': {'key': 'tenantId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceIdentity, self).__init__(**kwargs) + self.principal_id = None + self.type = kwargs.get('type', None) + self.tenant_id = None + + +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(TrackedResource, self).__init__(**kwargs) + self.tags = kwargs.get('tags', None) + self.location = kwargs['location'] + + +class Server(TrackedResource): + """Represents a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + :param identity: The Azure Active Directory identity of the server. + :type identity: ~azure.mgmt.rdbms.postgresql.models.ResourceIdentity + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.postgresql.models.Sku + :param administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). + :type administrator_login: str + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :ivar byok_enforcement: Status showing whether the server data encryption is enabled with + customer-managed keys. + :vartype byok_enforcement: str + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param user_visible_state: A state of a server that is visible to user. Possible values + include: "Ready", "Dropping", "Disabled", "Inaccessible". + :type user_visible_state: str or ~azure.mgmt.rdbms.postgresql.models.ServerState + :param fully_qualified_domain_name: The fully qualified domain name of a server. + :type fully_qualified_domain_name: str + :param earliest_restore_date: Earliest restore point creation time (ISO8601 format). + :type earliest_restore_date: ~datetime.datetime + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param replication_role: The replication role of the server. + :type replication_role: str + :param master_server_id: The master server id of a replica server. + :type master_server_id: str + :param replica_capacity: The maximum number of replicas that a master server can have. + :type replica_capacity: int + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :ivar private_endpoint_connections: List of private endpoint connections on a server. + :vartype private_endpoint_connections: + list[~azure.mgmt.rdbms.postgresql.models.ServerPrivateEndpointConnection] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + 'byok_enforcement': {'readonly': True}, + 'replica_capacity': {'minimum': 0}, + 'private_endpoint_connections': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'administrator_login': {'key': 'properties.administratorLogin', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, + 'byok_enforcement': {'key': 'properties.byokEnforcement', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'properties.infrastructureEncryption', 'type': 'str'}, + 'user_visible_state': {'key': 'properties.userVisibleState', 'type': 'str'}, + 'fully_qualified_domain_name': {'key': 'properties.fullyQualifiedDomainName', 'type': 'str'}, + 'earliest_restore_date': {'key': 'properties.earliestRestoreDate', 'type': 'iso-8601'}, + 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + 'master_server_id': {'key': 'properties.masterServerId', 'type': 'str'}, + 'replica_capacity': {'key': 'properties.replicaCapacity', 'type': 'int'}, + 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, + 'private_endpoint_connections': {'key': 'properties.privateEndpointConnections', 'type': '[ServerPrivateEndpointConnection]'}, + } + + def __init__( + self, + **kwargs + ): + super(Server, self).__init__(**kwargs) + self.identity = kwargs.get('identity', None) + self.sku = kwargs.get('sku', None) + self.administrator_login = kwargs.get('administrator_login', None) + self.version = kwargs.get('version', None) + self.ssl_enforcement = kwargs.get('ssl_enforcement', None) + self.minimal_tls_version = kwargs.get('minimal_tls_version', None) + self.byok_enforcement = None + self.infrastructure_encryption = kwargs.get('infrastructure_encryption', None) + self.user_visible_state = kwargs.get('user_visible_state', None) + self.fully_qualified_domain_name = kwargs.get('fully_qualified_domain_name', None) + self.earliest_restore_date = kwargs.get('earliest_restore_date', None) + self.storage_profile = kwargs.get('storage_profile', None) + self.replication_role = kwargs.get('replication_role', None) + self.master_server_id = kwargs.get('master_server_id', None) + self.replica_capacity = kwargs.get('replica_capacity', None) + self.public_network_access = kwargs.get('public_network_access', None) + self.private_endpoint_connections = None + + +class ServerAdministratorResource(ProxyResource): + """Represents a and external administrator to be created. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param administrator_type: The type of administrator. The only acceptable values to pass in are + None and "ActiveDirectory". The default value is None. + :type administrator_type: str + :param login: The server administrator login account name. + :type login: str + :param sid: The server administrator Sid (Secure ID). + :type sid: str + :param tenant_id: The server Active Directory Administrator tenant id. + :type tenant_id: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'administrator_type': {'key': 'properties.administratorType', 'type': 'str'}, + 'login': {'key': 'properties.login', 'type': 'str'}, + 'sid': {'key': 'properties.sid', 'type': 'str'}, + 'tenant_id': {'key': 'properties.tenantId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerAdministratorResource, self).__init__(**kwargs) + self.administrator_type = kwargs.get('administrator_type', None) + self.login = kwargs.get('login', None) + self.sid = kwargs.get('sid', None) + self.tenant_id = kwargs.get('tenant_id', None) + + +class ServerAdministratorResourceListResult(msrest.serialization.Model): + """The response to a list Active Directory Administrators request. + + :param value: The list of server Active Directory Administrators for the server. + :type value: list[~azure.mgmt.rdbms.postgresql.models.ServerAdministratorResource] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerAdministratorResource]'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerAdministratorResourceListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class ServerForCreate(msrest.serialization.Model): + """Represents a server to be created. + + All required parameters must be populated in order to send to Azure. + + :param identity: The Azure Active Directory identity of the server. + :type identity: ~azure.mgmt.rdbms.postgresql.models.ResourceIdentity + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.postgresql.models.Sku + :param properties: Required. Properties of the server. + :type properties: ~azure.mgmt.rdbms.postgresql.models.ServerPropertiesForCreate + :param location: Required. The location the resource resides in. + :type location: str + :param tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :type tags: dict[str, str] + """ + + _validation = { + 'properties': {'required': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'properties': {'key': 'properties', 'type': 'ServerPropertiesForCreate'}, + 'location': {'key': 'location', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerForCreate, self).__init__(**kwargs) + self.identity = kwargs.get('identity', None) + self.sku = kwargs.get('sku', None) + self.properties = kwargs['properties'] + self.location = kwargs['location'] + self.tags = kwargs.get('tags', None) + + +class ServerKey(ProxyResource): + """A PostgreSQL Server key. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar kind: Kind of encryption protector used to protect the key. + :vartype kind: str + :param server_key_type: The key type like 'AzureKeyVault'. Possible values include: + "AzureKeyVault". + :type server_key_type: str or ~azure.mgmt.rdbms.postgresql.models.ServerKeyType + :param uri: The URI of the key. + :type uri: str + :ivar creation_date: The key creation date. + :vartype creation_date: ~datetime.datetime + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'kind': {'readonly': True}, + 'creation_date': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'kind': {'key': 'kind', 'type': 'str'}, + 'server_key_type': {'key': 'properties.serverKeyType', 'type': 'str'}, + 'uri': {'key': 'properties.uri', 'type': 'str'}, + 'creation_date': {'key': 'properties.creationDate', 'type': 'iso-8601'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerKey, self).__init__(**kwargs) + self.kind = None + self.server_key_type = kwargs.get('server_key_type', None) + self.uri = kwargs.get('uri', None) + self.creation_date = None + + +class ServerKeyListResult(msrest.serialization.Model): + """A list of PostgreSQL Server keys. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: A list of PostgreSQL Server keys. + :vartype value: list[~azure.mgmt.rdbms.postgresql.models.ServerKey] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerKey]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerKeyListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ServerListResult(msrest.serialization.Model): + """A list of servers. + + :param value: The list of servers. + :type value: list[~azure.mgmt.rdbms.postgresql.models.Server] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Server]'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + + +class ServerPrivateEndpointConnection(msrest.serialization.Model): + """A private endpoint connection under a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource ID of the Private Endpoint Connection. + :vartype id: str + :ivar properties: Private endpoint connection properties. + :vartype properties: + ~azure.mgmt.rdbms.postgresql.models.ServerPrivateEndpointConnectionProperties + """ + + _validation = { + 'id': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'ServerPrivateEndpointConnectionProperties'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPrivateEndpointConnection, self).__init__(**kwargs) + self.id = None + self.properties = None + + +class ServerPrivateEndpointConnectionProperties(msrest.serialization.Model): + """Properties of a private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param private_endpoint: Private endpoint which the connection belongs to. + :type private_endpoint: ~azure.mgmt.rdbms.postgresql.models.PrivateEndpointProperty + :param private_link_service_connection_state: Connection state of the private endpoint + connection. + :type private_link_service_connection_state: + ~azure.mgmt.rdbms.postgresql.models.ServerPrivateLinkServiceConnectionStateProperty + :ivar provisioning_state: State of the private endpoint connection. Possible values include: + "Approving", "Ready", "Dropping", "Failed", "Rejecting". + :vartype provisioning_state: str or + ~azure.mgmt.rdbms.postgresql.models.PrivateEndpointProvisioningState + """ + + _validation = { + 'provisioning_state': {'readonly': True}, + } + + _attribute_map = { + 'private_endpoint': {'key': 'privateEndpoint', 'type': 'PrivateEndpointProperty'}, + 'private_link_service_connection_state': {'key': 'privateLinkServiceConnectionState', 'type': 'ServerPrivateLinkServiceConnectionStateProperty'}, + 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPrivateEndpointConnectionProperties, self).__init__(**kwargs) + self.private_endpoint = kwargs.get('private_endpoint', None) + self.private_link_service_connection_state = kwargs.get('private_link_service_connection_state', None) + self.provisioning_state = None + + +class ServerPrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): + """ServerPrivateLinkServiceConnectionStateProperty. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param status: Required. The private link service connection status. Possible values include: + "Approved", "Pending", "Rejected", "Disconnected". + :type status: str or + ~azure.mgmt.rdbms.postgresql.models.PrivateLinkServiceConnectionStateStatus + :param description: Required. The private link service connection description. + :type description: str + :ivar actions_required: The actions required for private link service connection. Possible + values include: "None". + :vartype actions_required: str or + ~azure.mgmt.rdbms.postgresql.models.PrivateLinkServiceConnectionStateActionsRequire + """ + + _validation = { + 'status': {'required': True}, + 'description': {'required': True}, + 'actions_required': {'readonly': True}, + } + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + self.status = kwargs['status'] + self.description = kwargs['description'] + self.actions_required = None + + +class ServerPropertiesForCreate(msrest.serialization.Model): + """The properties used to create a new server. + + You probably want to use the sub-classes and not this class directly. Known + sub-classes are: ServerPropertiesForDefaultCreate, ServerPropertiesForGeoRestore, ServerPropertiesForRestore, ServerPropertiesForReplica. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql.models.CreateMode + """ + + _validation = { + 'create_mode': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + } + + _subtype_map = { + 'create_mode': {'Default': 'ServerPropertiesForDefaultCreate', 'GeoRestore': 'ServerPropertiesForGeoRestore', 'PointInTimeRestore': 'ServerPropertiesForRestore', 'Replica': 'ServerPropertiesForReplica'} + } + + def __init__( + self, + **kwargs + ): + super(ServerPropertiesForCreate, self).__init__(**kwargs) + self.version = kwargs.get('version', None) + self.ssl_enforcement = kwargs.get('ssl_enforcement', None) + self.minimal_tls_version = kwargs.get('minimal_tls_version', None) + self.infrastructure_encryption = kwargs.get('infrastructure_encryption', None) + self.public_network_access = kwargs.get('public_network_access', None) + self.storage_profile = kwargs.get('storage_profile', None) + self.create_mode = None # type: Optional[str] + + +class ServerPropertiesForDefaultCreate(ServerPropertiesForCreate): + """The properties used to create a new server. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql.models.CreateMode + :param administrator_login: Required. The administrator's login name of a server. Can only be + specified when the server is being created (and is required for creation). + :type administrator_login: str + :param administrator_login_password: Required. The password of the administrator login. + :type administrator_login_password: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'administrator_login': {'required': True}, + 'administrator_login_password': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'administrator_login': {'key': 'administratorLogin', 'type': 'str'}, + 'administrator_login_password': {'key': 'administratorLoginPassword', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPropertiesForDefaultCreate, self).__init__(**kwargs) + self.create_mode = 'Default' # type: str + self.administrator_login = kwargs['administrator_login'] + self.administrator_login_password = kwargs['administrator_login_password'] + + +class ServerPropertiesForGeoRestore(ServerPropertiesForCreate): + """The properties used to create a new server by restoring to a different region from a geo replicated backup. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql.models.CreateMode + :param source_server_id: Required. The source server id to restore from. + :type source_server_id: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPropertiesForGeoRestore, self).__init__(**kwargs) + self.create_mode = 'GeoRestore' # type: str + self.source_server_id = kwargs['source_server_id'] + + +class ServerPropertiesForReplica(ServerPropertiesForCreate): + """The properties to create a new replica. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql.models.CreateMode + :param source_server_id: Required. The master server id to create replica from. + :type source_server_id: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPropertiesForReplica, self).__init__(**kwargs) + self.create_mode = 'Replica' # type: str + self.source_server_id = kwargs['source_server_id'] + + +class ServerPropertiesForRestore(ServerPropertiesForCreate): + """The properties used to create a new server by restoring from a backup. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql.models.CreateMode + :param source_server_id: Required. The source server id to restore from. + :type source_server_id: str + :param restore_point_in_time: Required. Restore point creation time (ISO8601 format), + specifying the time to restore from. + :type restore_point_in_time: ~datetime.datetime + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + 'restore_point_in_time': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + 'restore_point_in_time': {'key': 'restorePointInTime', 'type': 'iso-8601'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPropertiesForRestore, self).__init__(**kwargs) + self.create_mode = 'PointInTimeRestore' # type: str + self.source_server_id = kwargs['source_server_id'] + self.restore_point_in_time = kwargs['restore_point_in_time'] + + +class ServerSecurityAlertPolicy(ProxyResource): + """A server security alert policy. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param state: Specifies the state of the policy, whether it is enabled or disabled. Possible + values include: "Enabled", "Disabled". + :type state: str or ~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicyState + :param disabled_alerts: Specifies an array of alerts that are disabled. Allowed values are: + Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly. + :type disabled_alerts: list[str] + :param email_addresses: Specifies an array of e-mail addresses to which the alert is sent. + :type email_addresses: list[str] + :param email_account_admins: Specifies that the alert is sent to the account administrators. + :type email_account_admins: bool + :param storage_endpoint: Specifies the blob storage endpoint (e.g. + https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection + audit logs. + :type storage_endpoint: str + :param storage_account_access_key: Specifies the identifier key of the Threat Detection audit + storage account. + :type storage_account_access_key: str + :param retention_days: Specifies the number of days to keep in the Threat Detection audit logs. + :type retention_days: int + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + 'disabled_alerts': {'key': 'properties.disabledAlerts', 'type': '[str]'}, + 'email_addresses': {'key': 'properties.emailAddresses', 'type': '[str]'}, + 'email_account_admins': {'key': 'properties.emailAccountAdmins', 'type': 'bool'}, + 'storage_endpoint': {'key': 'properties.storageEndpoint', 'type': 'str'}, + 'storage_account_access_key': {'key': 'properties.storageAccountAccessKey', 'type': 'str'}, + 'retention_days': {'key': 'properties.retentionDays', 'type': 'int'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerSecurityAlertPolicy, self).__init__(**kwargs) + self.state = kwargs.get('state', None) + self.disabled_alerts = kwargs.get('disabled_alerts', None) + self.email_addresses = kwargs.get('email_addresses', None) + self.email_account_admins = kwargs.get('email_account_admins', None) + self.storage_endpoint = kwargs.get('storage_endpoint', None) + self.storage_account_access_key = kwargs.get('storage_account_access_key', None) + self.retention_days = kwargs.get('retention_days', None) + + +class ServerSecurityAlertPolicyListResult(msrest.serialization.Model): + """A list of the server's security alert policies. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicy] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerSecurityAlertPolicy]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerSecurityAlertPolicyListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ServerUpdateParameters(msrest.serialization.Model): + """Parameters allowed to update for a server. + + :param identity: The Azure Active Directory identity of the server. + :type identity: ~azure.mgmt.rdbms.postgresql.models.ResourceIdentity + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.postgresql.models.Sku + :param tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :type tags: dict[str, str] + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param administrator_login_password: The password of the administrator login. + :type administrator_login_password: str + :param version: The version of a server. Possible values include: "9.5", "9.6", "10", "10.0", + "10.2", "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param replication_role: The replication role of the server. + :type replication_role: str + """ + + _attribute_map = { + 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, + 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerUpdateParameters, self).__init__(**kwargs) + self.identity = kwargs.get('identity', None) + self.sku = kwargs.get('sku', None) + self.tags = kwargs.get('tags', None) + self.storage_profile = kwargs.get('storage_profile', None) + self.administrator_login_password = kwargs.get('administrator_login_password', None) + self.version = kwargs.get('version', None) + self.ssl_enforcement = kwargs.get('ssl_enforcement', None) + self.minimal_tls_version = kwargs.get('minimal_tls_version', None) + self.public_network_access = kwargs.get('public_network_access', None) + self.replication_role = kwargs.get('replication_role', None) + + +class Sku(msrest.serialization.Model): + """Billing information related properties of a server. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, + GP_Gen5_8. + :type name: str + :param tier: The tier of the particular SKU, e.g. Basic. Possible values include: "Basic", + "GeneralPurpose", "MemoryOptimized". + :type tier: str or ~azure.mgmt.rdbms.postgresql.models.SkuTier + :param capacity: The scale up/out capacity, representing server's compute units. + :type capacity: int + :param size: The size code, to be interpreted by resource as appropriate. + :type size: str + :param family: The family of hardware. + :type family: str + """ + + _validation = { + 'name': {'required': True}, + 'capacity': {'minimum': 0}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'tier': {'key': 'tier', 'type': 'str'}, + 'capacity': {'key': 'capacity', 'type': 'int'}, + 'size': {'key': 'size', 'type': 'str'}, + 'family': {'key': 'family', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Sku, self).__init__(**kwargs) + self.name = kwargs['name'] + self.tier = kwargs.get('tier', None) + self.capacity = kwargs.get('capacity', None) + self.size = kwargs.get('size', None) + self.family = kwargs.get('family', None) + + +class StorageProfile(msrest.serialization.Model): + """Storage Profile properties of a server. + + :param backup_retention_days: Backup retention days for the server. + :type backup_retention_days: int + :param geo_redundant_backup: Enable Geo-redundant or not for server backup. Possible values + include: "Enabled", "Disabled". + :type geo_redundant_backup: str or ~azure.mgmt.rdbms.postgresql.models.GeoRedundantBackup + :param storage_mb: Max storage allowed for a server. + :type storage_mb: int + :param storage_autogrow: Enable Storage Auto Grow. Possible values include: "Enabled", + "Disabled". + :type storage_autogrow: str or ~azure.mgmt.rdbms.postgresql.models.StorageAutogrow + """ + + _attribute_map = { + 'backup_retention_days': {'key': 'backupRetentionDays', 'type': 'int'}, + 'geo_redundant_backup': {'key': 'geoRedundantBackup', 'type': 'str'}, + 'storage_mb': {'key': 'storageMB', 'type': 'int'}, + 'storage_autogrow': {'key': 'storageAutogrow', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(StorageProfile, self).__init__(**kwargs) + self.backup_retention_days = kwargs.get('backup_retention_days', None) + self.geo_redundant_backup = kwargs.get('geo_redundant_backup', None) + self.storage_mb = kwargs.get('storage_mb', None) + self.storage_autogrow = kwargs.get('storage_autogrow', None) + + +class TagsObject(msrest.serialization.Model): + """Tags object for patch operations. + + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + """ + + _attribute_map = { + 'tags': {'key': 'tags', 'type': '{str}'}, + } + + def __init__( + self, + **kwargs + ): + super(TagsObject, self).__init__(**kwargs) + self.tags = kwargs.get('tags', None) + + +class VirtualNetworkRule(ProxyResource): + """A virtual network rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param virtual_network_subnet_id: The ARM resource id of the virtual network subnet. + :type virtual_network_subnet_id: str + :param ignore_missing_vnet_service_endpoint: Create firewall rule before the virtual network + has vnet service endpoint enabled. + :type ignore_missing_vnet_service_endpoint: bool + :ivar state: Virtual Network Rule State. Possible values include: "Initializing", "InProgress", + "Ready", "Deleting", "Unknown". + :vartype state: str or ~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRuleState + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'state': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'virtual_network_subnet_id': {'key': 'properties.virtualNetworkSubnetId', 'type': 'str'}, + 'ignore_missing_vnet_service_endpoint': {'key': 'properties.ignoreMissingVnetServiceEndpoint', 'type': 'bool'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(VirtualNetworkRule, self).__init__(**kwargs) + self.virtual_network_subnet_id = kwargs.get('virtual_network_subnet_id', None) + self.ignore_missing_vnet_service_endpoint = kwargs.get('ignore_missing_vnet_service_endpoint', None) + self.state = None + + +class VirtualNetworkRuleListResult(msrest.serialization.Model): + """A list of virtual network rules. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRule] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[VirtualNetworkRule]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(VirtualNetworkRuleListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..c270ac23040f21410406bcf6caeadc31683b27d1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/_models_py3.py @@ -0,0 +1,2358 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import Dict, List, Optional, Union + +import msrest.serialization + +from ._postgre_sql_management_client_enums import * + + +class Resource(msrest.serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class Configuration(ProxyResource): + """Represents a Configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param value: Value of the configuration. + :type value: str + :ivar description: Description of the configuration. + :vartype description: str + :ivar default_value: Default value of the configuration. + :vartype default_value: str + :ivar data_type: Data type of the configuration. + :vartype data_type: str + :ivar allowed_values: Allowed values of the configuration. + :vartype allowed_values: str + :param source: Source of the configuration. + :type source: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'description': {'readonly': True}, + 'default_value': {'readonly': True}, + 'data_type': {'readonly': True}, + 'allowed_values': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'value': {'key': 'properties.value', 'type': 'str'}, + 'description': {'key': 'properties.description', 'type': 'str'}, + 'default_value': {'key': 'properties.defaultValue', 'type': 'str'}, + 'data_type': {'key': 'properties.dataType', 'type': 'str'}, + 'allowed_values': {'key': 'properties.allowedValues', 'type': 'str'}, + 'source': {'key': 'properties.source', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[str] = None, + source: Optional[str] = None, + **kwargs + ): + super(Configuration, self).__init__(**kwargs) + self.value = value + self.description = None + self.default_value = None + self.data_type = None + self.allowed_values = None + self.source = source + + +class ConfigurationListResult(msrest.serialization.Model): + """A list of server configurations. + + :param value: The list of server configurations. + :type value: list[~azure.mgmt.rdbms.postgresql.models.Configuration] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Configuration]'}, + } + + def __init__( + self, + *, + value: Optional[List["Configuration"]] = None, + **kwargs + ): + super(ConfigurationListResult, self).__init__(**kwargs) + self.value = value + + +class Database(ProxyResource): + """Represents a Database. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param charset: The charset of the database. + :type charset: str + :param collation: The collation of the database. + :type collation: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'charset': {'key': 'properties.charset', 'type': 'str'}, + 'collation': {'key': 'properties.collation', 'type': 'str'}, + } + + def __init__( + self, + *, + charset: Optional[str] = None, + collation: Optional[str] = None, + **kwargs + ): + super(Database, self).__init__(**kwargs) + self.charset = charset + self.collation = collation + + +class DatabaseListResult(msrest.serialization.Model): + """A List of databases. + + :param value: The list of databases housed in a server. + :type value: list[~azure.mgmt.rdbms.postgresql.models.Database] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Database]'}, + } + + def __init__( + self, + *, + value: Optional[List["Database"]] = None, + **kwargs + ): + super(DatabaseListResult, self).__init__(**kwargs) + self.value = value + + +class ErrorAdditionalInfo(msrest.serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorResponse(msrest.serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.rdbms.postgresql.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.rdbms.postgresql.models.ErrorAdditionalInfo] + """ + + _validation = { + 'code': {'readonly': True}, + 'message': {'readonly': True}, + 'target': {'readonly': True}, + 'details': {'readonly': True}, + 'additional_info': {'readonly': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'target': {'key': 'target', 'type': 'str'}, + 'details': {'key': 'details', 'type': '[ErrorResponse]'}, + 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class FirewallRule(ProxyResource): + """Represents a server firewall rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param start_ip_address: Required. The start IP address of the server firewall rule. Must be + IPv4 format. + :type start_ip_address: str + :param end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 + format. + :type end_ip_address: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'start_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + 'end_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'start_ip_address': {'key': 'properties.startIpAddress', 'type': 'str'}, + 'end_ip_address': {'key': 'properties.endIpAddress', 'type': 'str'}, + } + + def __init__( + self, + *, + start_ip_address: str, + end_ip_address: str, + **kwargs + ): + super(FirewallRule, self).__init__(**kwargs) + self.start_ip_address = start_ip_address + self.end_ip_address = end_ip_address + + +class FirewallRuleListResult(msrest.serialization.Model): + """A list of firewall rules. + + :param value: The list of firewall rules in a server. + :type value: list[~azure.mgmt.rdbms.postgresql.models.FirewallRule] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FirewallRule]'}, + } + + def __init__( + self, + *, + value: Optional[List["FirewallRule"]] = None, + **kwargs + ): + super(FirewallRuleListResult, self).__init__(**kwargs) + self.value = value + + +class LogFile(ProxyResource): + """Represents a log file. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param size_in_kb: Size of the log file. + :type size_in_kb: long + :ivar created_time: Creation timestamp of the log file. + :vartype created_time: ~datetime.datetime + :ivar last_modified_time: Last modified timestamp of the log file. + :vartype last_modified_time: ~datetime.datetime + :param type_properties_type: Type of the log file. + :type type_properties_type: str + :param url: The url to download the log file from. + :type url: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'created_time': {'readonly': True}, + 'last_modified_time': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'size_in_kb': {'key': 'properties.sizeInKB', 'type': 'long'}, + 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, + 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'iso-8601'}, + 'type_properties_type': {'key': 'properties.type', 'type': 'str'}, + 'url': {'key': 'properties.url', 'type': 'str'}, + } + + def __init__( + self, + *, + size_in_kb: Optional[int] = None, + type_properties_type: Optional[str] = None, + url: Optional[str] = None, + **kwargs + ): + super(LogFile, self).__init__(**kwargs) + self.size_in_kb = size_in_kb + self.created_time = None + self.last_modified_time = None + self.type_properties_type = type_properties_type + self.url = url + + +class LogFileListResult(msrest.serialization.Model): + """A list of log files. + + :param value: The list of log files. + :type value: list[~azure.mgmt.rdbms.postgresql.models.LogFile] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[LogFile]'}, + } + + def __init__( + self, + *, + value: Optional[List["LogFile"]] = None, + **kwargs + ): + super(LogFileListResult, self).__init__(**kwargs) + self.value = value + + +class NameAvailability(msrest.serialization.Model): + """Represents a resource name availability. + + :param message: Error Message. + :type message: str + :param name_available: Indicates whether the resource name is available. + :type name_available: bool + :param reason: Reason for name being unavailable. + :type reason: str + """ + + _attribute_map = { + 'message': {'key': 'message', 'type': 'str'}, + 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, + 'reason': {'key': 'reason', 'type': 'str'}, + } + + def __init__( + self, + *, + message: Optional[str] = None, + name_available: Optional[bool] = None, + reason: Optional[str] = None, + **kwargs + ): + super(NameAvailability, self).__init__(**kwargs) + self.message = message + self.name_available = name_available + self.reason = reason + + +class NameAvailabilityRequest(msrest.serialization.Model): + """Request from client to check resource name availability. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. Resource name to verify. + :type name: str + :param type: Resource type used for verification. + :type type: str + """ + + _validation = { + 'name': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + name: str, + type: Optional[str] = None, + **kwargs + ): + super(NameAvailabilityRequest, self).__init__(**kwargs) + self.name = name + self.type = type + + +class Operation(msrest.serialization.Model): + """REST API operation definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation being performed on this particular object. + :vartype name: str + :ivar display: The localized display information for this particular operation or action. + :vartype display: ~azure.mgmt.rdbms.postgresql.models.OperationDisplay + :ivar origin: The intended executor of the operation. Possible values include: "NotSpecified", + "user", "system". + :vartype origin: str or ~azure.mgmt.rdbms.postgresql.models.OperationOrigin + :ivar properties: Additional descriptions for the operation. + :vartype properties: dict[str, any] + """ + + _validation = { + 'name': {'readonly': True}, + 'display': {'readonly': True}, + 'origin': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'OperationDisplay'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{object}'}, + } + + def __init__( + self, + **kwargs + ): + super(Operation, self).__init__(**kwargs) + self.name = None + self.display = None + self.origin = None + self.properties = None + + +class OperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: Operation resource provider name. + :vartype provider: str + :ivar resource: Resource on which the operation is performed. + :vartype resource: str + :ivar operation: Localized friendly name for the operation. + :vartype operation: str + :ivar description: Operation description. + :vartype description: str + """ + + _validation = { + 'provider': {'readonly': True}, + 'resource': {'readonly': True}, + 'operation': {'readonly': True}, + 'description': {'readonly': True}, + } + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationDisplay, self).__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(msrest.serialization.Model): + """A list of resource provider operations. + + :param value: The list of resource provider operations. + :type value: list[~azure.mgmt.rdbms.postgresql.models.Operation] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Operation]'}, + } + + def __init__( + self, + *, + value: Optional[List["Operation"]] = None, + **kwargs + ): + super(OperationListResult, self).__init__(**kwargs) + self.value = value + + +class PerformanceTierListResult(msrest.serialization.Model): + """A list of performance tiers. + + :param value: The list of performance tiers. + :type value: list[~azure.mgmt.rdbms.postgresql.models.PerformanceTierProperties] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PerformanceTierProperties]'}, + } + + def __init__( + self, + *, + value: Optional[List["PerformanceTierProperties"]] = None, + **kwargs + ): + super(PerformanceTierListResult, self).__init__(**kwargs) + self.value = value + + +class PerformanceTierProperties(msrest.serialization.Model): + """Performance tier properties. + + :param id: ID of the performance tier. + :type id: str + :param max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :type max_backup_retention_days: int + :param min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :type min_backup_retention_days: int + :param max_storage_mb: Max storage allowed for a server. + :type max_storage_mb: int + :param min_large_storage_mb: Max storage allowed for a server. + :type min_large_storage_mb: int + :param max_large_storage_mb: Max storage allowed for a server. + :type max_large_storage_mb: int + :param min_storage_mb: Max storage allowed for a server. + :type min_storage_mb: int + :param service_level_objectives: Service level objectives associated with the performance tier. + :type service_level_objectives: + list[~azure.mgmt.rdbms.postgresql.models.PerformanceTierServiceLevelObjectives] + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, + 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, + 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, + 'min_large_storage_mb': {'key': 'minLargeStorageMB', 'type': 'int'}, + 'max_large_storage_mb': {'key': 'maxLargeStorageMB', 'type': 'int'}, + 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, + 'service_level_objectives': {'key': 'serviceLevelObjectives', 'type': '[PerformanceTierServiceLevelObjectives]'}, + } + + def __init__( + self, + *, + id: Optional[str] = None, + max_backup_retention_days: Optional[int] = None, + min_backup_retention_days: Optional[int] = None, + max_storage_mb: Optional[int] = None, + min_large_storage_mb: Optional[int] = None, + max_large_storage_mb: Optional[int] = None, + min_storage_mb: Optional[int] = None, + service_level_objectives: Optional[List["PerformanceTierServiceLevelObjectives"]] = None, + **kwargs + ): + super(PerformanceTierProperties, self).__init__(**kwargs) + self.id = id + self.max_backup_retention_days = max_backup_retention_days + self.min_backup_retention_days = min_backup_retention_days + self.max_storage_mb = max_storage_mb + self.min_large_storage_mb = min_large_storage_mb + self.max_large_storage_mb = max_large_storage_mb + self.min_storage_mb = min_storage_mb + self.service_level_objectives = service_level_objectives + + +class PerformanceTierServiceLevelObjectives(msrest.serialization.Model): + """Service level objectives for performance tier. + + :param id: ID for the service level objective. + :type id: str + :param edition: Edition of the performance tier. + :type edition: str + :param v_core: vCore associated with the service level objective. + :type v_core: int + :param hardware_generation: Hardware generation associated with the service level objective. + :type hardware_generation: str + :param max_backup_retention_days: Maximum Backup retention in days for the performance tier + edition. + :type max_backup_retention_days: int + :param min_backup_retention_days: Minimum Backup retention in days for the performance tier + edition. + :type min_backup_retention_days: int + :param max_storage_mb: Max storage allowed for a server. + :type max_storage_mb: int + :param min_storage_mb: Max storage allowed for a server. + :type min_storage_mb: int + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'edition': {'key': 'edition', 'type': 'str'}, + 'v_core': {'key': 'vCore', 'type': 'int'}, + 'hardware_generation': {'key': 'hardwareGeneration', 'type': 'str'}, + 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, + 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, + 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, + 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, + } + + def __init__( + self, + *, + id: Optional[str] = None, + edition: Optional[str] = None, + v_core: Optional[int] = None, + hardware_generation: Optional[str] = None, + max_backup_retention_days: Optional[int] = None, + min_backup_retention_days: Optional[int] = None, + max_storage_mb: Optional[int] = None, + min_storage_mb: Optional[int] = None, + **kwargs + ): + super(PerformanceTierServiceLevelObjectives, self).__init__(**kwargs) + self.id = id + self.edition = edition + self.v_core = v_core + self.hardware_generation = hardware_generation + self.max_backup_retention_days = max_backup_retention_days + self.min_backup_retention_days = min_backup_retention_days + self.max_storage_mb = max_storage_mb + self.min_storage_mb = min_storage_mb + + +class PrivateEndpointConnection(ProxyResource): + """A private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param private_endpoint: Private endpoint which the connection belongs to. + :type private_endpoint: ~azure.mgmt.rdbms.postgresql.models.PrivateEndpointProperty + :param private_link_service_connection_state: Connection state of the private endpoint + connection. + :type private_link_service_connection_state: + ~azure.mgmt.rdbms.postgresql.models.PrivateLinkServiceConnectionStateProperty + :ivar provisioning_state: State of the private endpoint connection. + :vartype provisioning_state: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpointProperty'}, + 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionStateProperty'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + } + + def __init__( + self, + *, + private_endpoint: Optional["PrivateEndpointProperty"] = None, + private_link_service_connection_state: Optional["PrivateLinkServiceConnectionStateProperty"] = None, + **kwargs + ): + super(PrivateEndpointConnection, self).__init__(**kwargs) + self.private_endpoint = private_endpoint + self.private_link_service_connection_state = private_link_service_connection_state + self.provisioning_state = None + + +class PrivateEndpointConnectionListResult(msrest.serialization.Model): + """A list of private endpoint connections. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnection] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PrivateEndpointConnection]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateEndpointConnectionListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class PrivateEndpointProperty(msrest.serialization.Model): + """PrivateEndpointProperty. + + :param id: Resource id of the private endpoint. + :type id: str + """ + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + } + + def __init__( + self, + *, + id: Optional[str] = None, + **kwargs + ): + super(PrivateEndpointProperty, self).__init__(**kwargs) + self.id = id + + +class PrivateLinkResource(ProxyResource): + """A private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar properties: The private link resource group id. + :vartype properties: ~azure.mgmt.rdbms.postgresql.models.PrivateLinkResourceProperties + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'PrivateLinkResourceProperties'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResource, self).__init__(**kwargs) + self.properties = None + + +class PrivateLinkResourceListResult(msrest.serialization.Model): + """A list of private link resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.postgresql.models.PrivateLinkResource] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[PrivateLinkResource]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResourceListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class PrivateLinkResourceProperties(msrest.serialization.Model): + """Properties of a private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar group_id: The private link resource group id. + :vartype group_id: str + :ivar required_members: The private link resource required member names. + :vartype required_members: list[str] + """ + + _validation = { + 'group_id': {'readonly': True}, + 'required_members': {'readonly': True}, + } + + _attribute_map = { + 'group_id': {'key': 'groupId', 'type': 'str'}, + 'required_members': {'key': 'requiredMembers', 'type': '[str]'}, + } + + def __init__( + self, + **kwargs + ): + super(PrivateLinkResourceProperties, self).__init__(**kwargs) + self.group_id = None + self.required_members = None + + +class PrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): + """PrivateLinkServiceConnectionStateProperty. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param status: Required. The private link service connection status. + :type status: str + :param description: Required. The private link service connection description. + :type description: str + :ivar actions_required: The actions required for private link service connection. + :vartype actions_required: str + """ + + _validation = { + 'status': {'required': True}, + 'description': {'required': True}, + 'actions_required': {'readonly': True}, + } + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + } + + def __init__( + self, + *, + status: str, + description: str, + **kwargs + ): + super(PrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + self.status = status + self.description = description + self.actions_required = None + + +class RecoverableServerResource(ProxyResource): + """A recoverable server resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar last_available_backup_date_time: The last available backup date time. + :vartype last_available_backup_date_time: str + :ivar service_level_objective: The service level objective. + :vartype service_level_objective: str + :ivar edition: Edition of the performance tier. + :vartype edition: str + :ivar v_core: vCore associated with the service level objective. + :vartype v_core: int + :ivar hardware_generation: Hardware generation associated with the service level objective. + :vartype hardware_generation: str + :ivar version: The PostgreSQL version. + :vartype version: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'last_available_backup_date_time': {'readonly': True}, + 'service_level_objective': {'readonly': True}, + 'edition': {'readonly': True}, + 'v_core': {'readonly': True}, + 'hardware_generation': {'readonly': True}, + 'version': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'last_available_backup_date_time': {'key': 'properties.lastAvailableBackupDateTime', 'type': 'str'}, + 'service_level_objective': {'key': 'properties.serviceLevelObjective', 'type': 'str'}, + 'edition': {'key': 'properties.edition', 'type': 'str'}, + 'v_core': {'key': 'properties.vCore', 'type': 'int'}, + 'hardware_generation': {'key': 'properties.hardwareGeneration', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RecoverableServerResource, self).__init__(**kwargs) + self.last_available_backup_date_time = None + self.service_level_objective = None + self.edition = None + self.v_core = None + self.hardware_generation = None + self.version = None + + +class ResourceIdentity(msrest.serialization.Model): + """Azure Active Directory identity configuration for a resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The Azure Active Directory principal id. + :vartype principal_id: str + :param type: The identity type. Set this to 'SystemAssigned' in order to automatically create + and assign an Azure Active Directory principal for the resource. Possible values include: + "SystemAssigned". + :type type: str or ~azure.mgmt.rdbms.postgresql.models.IdentityType + :ivar tenant_id: The Azure Active Directory tenant id. + :vartype tenant_id: str + """ + + _validation = { + 'principal_id': {'readonly': True}, + 'tenant_id': {'readonly': True}, + } + + _attribute_map = { + 'principal_id': {'key': 'principalId', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tenant_id': {'key': 'tenantId', 'type': 'str'}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "IdentityType"]] = None, + **kwargs + ): + super(ResourceIdentity, self).__init__(**kwargs) + self.principal_id = None + self.type = type + self.tenant_id = None + + +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + **kwargs + ): + super(TrackedResource, self).__init__(**kwargs) + self.tags = tags + self.location = location + + +class Server(TrackedResource): + """Represents a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + :param identity: The Azure Active Directory identity of the server. + :type identity: ~azure.mgmt.rdbms.postgresql.models.ResourceIdentity + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.postgresql.models.Sku + :param administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). + :type administrator_login: str + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :ivar byok_enforcement: Status showing whether the server data encryption is enabled with + customer-managed keys. + :vartype byok_enforcement: str + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param user_visible_state: A state of a server that is visible to user. Possible values + include: "Ready", "Dropping", "Disabled", "Inaccessible". + :type user_visible_state: str or ~azure.mgmt.rdbms.postgresql.models.ServerState + :param fully_qualified_domain_name: The fully qualified domain name of a server. + :type fully_qualified_domain_name: str + :param earliest_restore_date: Earliest restore point creation time (ISO8601 format). + :type earliest_restore_date: ~datetime.datetime + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param replication_role: The replication role of the server. + :type replication_role: str + :param master_server_id: The master server id of a replica server. + :type master_server_id: str + :param replica_capacity: The maximum number of replicas that a master server can have. + :type replica_capacity: int + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :ivar private_endpoint_connections: List of private endpoint connections on a server. + :vartype private_endpoint_connections: + list[~azure.mgmt.rdbms.postgresql.models.ServerPrivateEndpointConnection] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + 'byok_enforcement': {'readonly': True}, + 'replica_capacity': {'minimum': 0}, + 'private_endpoint_connections': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'administrator_login': {'key': 'properties.administratorLogin', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, + 'byok_enforcement': {'key': 'properties.byokEnforcement', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'properties.infrastructureEncryption', 'type': 'str'}, + 'user_visible_state': {'key': 'properties.userVisibleState', 'type': 'str'}, + 'fully_qualified_domain_name': {'key': 'properties.fullyQualifiedDomainName', 'type': 'str'}, + 'earliest_restore_date': {'key': 'properties.earliestRestoreDate', 'type': 'iso-8601'}, + 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + 'master_server_id': {'key': 'properties.masterServerId', 'type': 'str'}, + 'replica_capacity': {'key': 'properties.replicaCapacity', 'type': 'int'}, + 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, + 'private_endpoint_connections': {'key': 'properties.privateEndpointConnections', 'type': '[ServerPrivateEndpointConnection]'}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + identity: Optional["ResourceIdentity"] = None, + sku: Optional["Sku"] = None, + administrator_login: Optional[str] = None, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + user_visible_state: Optional[Union[str, "ServerState"]] = None, + fully_qualified_domain_name: Optional[str] = None, + earliest_restore_date: Optional[datetime.datetime] = None, + storage_profile: Optional["StorageProfile"] = None, + replication_role: Optional[str] = None, + master_server_id: Optional[str] = None, + replica_capacity: Optional[int] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + **kwargs + ): + super(Server, self).__init__(tags=tags, location=location, **kwargs) + self.identity = identity + self.sku = sku + self.administrator_login = administrator_login + self.version = version + self.ssl_enforcement = ssl_enforcement + self.minimal_tls_version = minimal_tls_version + self.byok_enforcement = None + self.infrastructure_encryption = infrastructure_encryption + self.user_visible_state = user_visible_state + self.fully_qualified_domain_name = fully_qualified_domain_name + self.earliest_restore_date = earliest_restore_date + self.storage_profile = storage_profile + self.replication_role = replication_role + self.master_server_id = master_server_id + self.replica_capacity = replica_capacity + self.public_network_access = public_network_access + self.private_endpoint_connections = None + + +class ServerAdministratorResource(ProxyResource): + """Represents a and external administrator to be created. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param administrator_type: The type of administrator. The only acceptable values to pass in are + None and "ActiveDirectory". The default value is None. + :type administrator_type: str + :param login: The server administrator login account name. + :type login: str + :param sid: The server administrator Sid (Secure ID). + :type sid: str + :param tenant_id: The server Active Directory Administrator tenant id. + :type tenant_id: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'administrator_type': {'key': 'properties.administratorType', 'type': 'str'}, + 'login': {'key': 'properties.login', 'type': 'str'}, + 'sid': {'key': 'properties.sid', 'type': 'str'}, + 'tenant_id': {'key': 'properties.tenantId', 'type': 'str'}, + } + + def __init__( + self, + *, + administrator_type: Optional[str] = None, + login: Optional[str] = None, + sid: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs + ): + super(ServerAdministratorResource, self).__init__(**kwargs) + self.administrator_type = administrator_type + self.login = login + self.sid = sid + self.tenant_id = tenant_id + + +class ServerAdministratorResourceListResult(msrest.serialization.Model): + """The response to a list Active Directory Administrators request. + + :param value: The list of server Active Directory Administrators for the server. + :type value: list[~azure.mgmt.rdbms.postgresql.models.ServerAdministratorResource] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerAdministratorResource]'}, + } + + def __init__( + self, + *, + value: Optional[List["ServerAdministratorResource"]] = None, + **kwargs + ): + super(ServerAdministratorResourceListResult, self).__init__(**kwargs) + self.value = value + + +class ServerForCreate(msrest.serialization.Model): + """Represents a server to be created. + + All required parameters must be populated in order to send to Azure. + + :param identity: The Azure Active Directory identity of the server. + :type identity: ~azure.mgmt.rdbms.postgresql.models.ResourceIdentity + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.postgresql.models.Sku + :param properties: Required. Properties of the server. + :type properties: ~azure.mgmt.rdbms.postgresql.models.ServerPropertiesForCreate + :param location: Required. The location the resource resides in. + :type location: str + :param tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :type tags: dict[str, str] + """ + + _validation = { + 'properties': {'required': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'properties': {'key': 'properties', 'type': 'ServerPropertiesForCreate'}, + 'location': {'key': 'location', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + } + + def __init__( + self, + *, + properties: "ServerPropertiesForCreate", + location: str, + identity: Optional["ResourceIdentity"] = None, + sku: Optional["Sku"] = None, + tags: Optional[Dict[str, str]] = None, + **kwargs + ): + super(ServerForCreate, self).__init__(**kwargs) + self.identity = identity + self.sku = sku + self.properties = properties + self.location = location + self.tags = tags + + +class ServerKey(ProxyResource): + """A PostgreSQL Server key. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar kind: Kind of encryption protector used to protect the key. + :vartype kind: str + :param server_key_type: The key type like 'AzureKeyVault'. Possible values include: + "AzureKeyVault". + :type server_key_type: str or ~azure.mgmt.rdbms.postgresql.models.ServerKeyType + :param uri: The URI of the key. + :type uri: str + :ivar creation_date: The key creation date. + :vartype creation_date: ~datetime.datetime + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'kind': {'readonly': True}, + 'creation_date': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'kind': {'key': 'kind', 'type': 'str'}, + 'server_key_type': {'key': 'properties.serverKeyType', 'type': 'str'}, + 'uri': {'key': 'properties.uri', 'type': 'str'}, + 'creation_date': {'key': 'properties.creationDate', 'type': 'iso-8601'}, + } + + def __init__( + self, + *, + server_key_type: Optional[Union[str, "ServerKeyType"]] = None, + uri: Optional[str] = None, + **kwargs + ): + super(ServerKey, self).__init__(**kwargs) + self.kind = None + self.server_key_type = server_key_type + self.uri = uri + self.creation_date = None + + +class ServerKeyListResult(msrest.serialization.Model): + """A list of PostgreSQL Server keys. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: A list of PostgreSQL Server keys. + :vartype value: list[~azure.mgmt.rdbms.postgresql.models.ServerKey] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerKey]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerKeyListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ServerListResult(msrest.serialization.Model): + """A list of servers. + + :param value: The list of servers. + :type value: list[~azure.mgmt.rdbms.postgresql.models.Server] + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Server]'}, + } + + def __init__( + self, + *, + value: Optional[List["Server"]] = None, + **kwargs + ): + super(ServerListResult, self).__init__(**kwargs) + self.value = value + + +class ServerPrivateEndpointConnection(msrest.serialization.Model): + """A private endpoint connection under a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource ID of the Private Endpoint Connection. + :vartype id: str + :ivar properties: Private endpoint connection properties. + :vartype properties: + ~azure.mgmt.rdbms.postgresql.models.ServerPrivateEndpointConnectionProperties + """ + + _validation = { + 'id': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'ServerPrivateEndpointConnectionProperties'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerPrivateEndpointConnection, self).__init__(**kwargs) + self.id = None + self.properties = None + + +class ServerPrivateEndpointConnectionProperties(msrest.serialization.Model): + """Properties of a private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param private_endpoint: Private endpoint which the connection belongs to. + :type private_endpoint: ~azure.mgmt.rdbms.postgresql.models.PrivateEndpointProperty + :param private_link_service_connection_state: Connection state of the private endpoint + connection. + :type private_link_service_connection_state: + ~azure.mgmt.rdbms.postgresql.models.ServerPrivateLinkServiceConnectionStateProperty + :ivar provisioning_state: State of the private endpoint connection. Possible values include: + "Approving", "Ready", "Dropping", "Failed", "Rejecting". + :vartype provisioning_state: str or + ~azure.mgmt.rdbms.postgresql.models.PrivateEndpointProvisioningState + """ + + _validation = { + 'provisioning_state': {'readonly': True}, + } + + _attribute_map = { + 'private_endpoint': {'key': 'privateEndpoint', 'type': 'PrivateEndpointProperty'}, + 'private_link_service_connection_state': {'key': 'privateLinkServiceConnectionState', 'type': 'ServerPrivateLinkServiceConnectionStateProperty'}, + 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, + } + + def __init__( + self, + *, + private_endpoint: Optional["PrivateEndpointProperty"] = None, + private_link_service_connection_state: Optional["ServerPrivateLinkServiceConnectionStateProperty"] = None, + **kwargs + ): + super(ServerPrivateEndpointConnectionProperties, self).__init__(**kwargs) + self.private_endpoint = private_endpoint + self.private_link_service_connection_state = private_link_service_connection_state + self.provisioning_state = None + + +class ServerPrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): + """ServerPrivateLinkServiceConnectionStateProperty. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param status: Required. The private link service connection status. Possible values include: + "Approved", "Pending", "Rejected", "Disconnected". + :type status: str or + ~azure.mgmt.rdbms.postgresql.models.PrivateLinkServiceConnectionStateStatus + :param description: Required. The private link service connection description. + :type description: str + :ivar actions_required: The actions required for private link service connection. Possible + values include: "None". + :vartype actions_required: str or + ~azure.mgmt.rdbms.postgresql.models.PrivateLinkServiceConnectionStateActionsRequire + """ + + _validation = { + 'status': {'required': True}, + 'description': {'required': True}, + 'actions_required': {'readonly': True}, + } + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + } + + def __init__( + self, + *, + status: Union[str, "PrivateLinkServiceConnectionStateStatus"], + description: str, + **kwargs + ): + super(ServerPrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + self.status = status + self.description = description + self.actions_required = None + + +class ServerPropertiesForCreate(msrest.serialization.Model): + """The properties used to create a new server. + + You probably want to use the sub-classes and not this class directly. Known + sub-classes are: ServerPropertiesForDefaultCreate, ServerPropertiesForGeoRestore, ServerPropertiesForRestore, ServerPropertiesForReplica. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql.models.CreateMode + """ + + _validation = { + 'create_mode': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + } + + _subtype_map = { + 'create_mode': {'Default': 'ServerPropertiesForDefaultCreate', 'GeoRestore': 'ServerPropertiesForGeoRestore', 'PointInTimeRestore': 'ServerPropertiesForRestore', 'Replica': 'ServerPropertiesForReplica'} + } + + def __init__( + self, + *, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + super(ServerPropertiesForCreate, self).__init__(**kwargs) + self.version = version + self.ssl_enforcement = ssl_enforcement + self.minimal_tls_version = minimal_tls_version + self.infrastructure_encryption = infrastructure_encryption + self.public_network_access = public_network_access + self.storage_profile = storage_profile + self.create_mode = None # type: Optional[str] + + +class ServerPropertiesForDefaultCreate(ServerPropertiesForCreate): + """The properties used to create a new server. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql.models.CreateMode + :param administrator_login: Required. The administrator's login name of a server. Can only be + specified when the server is being created (and is required for creation). + :type administrator_login: str + :param administrator_login_password: Required. The password of the administrator login. + :type administrator_login_password: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'administrator_login': {'required': True}, + 'administrator_login_password': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'administrator_login': {'key': 'administratorLogin', 'type': 'str'}, + 'administrator_login_password': {'key': 'administratorLoginPassword', 'type': 'str'}, + } + + def __init__( + self, + *, + administrator_login: str, + administrator_login_password: str, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + super(ServerPropertiesForDefaultCreate, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'Default' # type: str + self.administrator_login = administrator_login + self.administrator_login_password = administrator_login_password + + +class ServerPropertiesForGeoRestore(ServerPropertiesForCreate): + """The properties used to create a new server by restoring to a different region from a geo replicated backup. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql.models.CreateMode + :param source_server_id: Required. The source server id to restore from. + :type source_server_id: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + } + + def __init__( + self, + *, + source_server_id: str, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + super(ServerPropertiesForGeoRestore, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'GeoRestore' # type: str + self.source_server_id = source_server_id + + +class ServerPropertiesForReplica(ServerPropertiesForCreate): + """The properties to create a new replica. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql.models.CreateMode + :param source_server_id: Required. The master server id to create replica from. + :type source_server_id: str + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + } + + def __init__( + self, + *, + source_server_id: str, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + super(ServerPropertiesForReplica, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'Replica' # type: str + self.source_server_id = source_server_id + + +class ServerPropertiesForRestore(ServerPropertiesForCreate): + """The properties used to create a new server by restoring from a backup. + + All required parameters must be populated in order to send to Azure. + + :param version: Server version. Possible values include: "9.5", "9.6", "10", "10.0", "10.2", + "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param infrastructure_encryption: Status showing whether the server enabled infrastructure + encryption. Possible values include: "Enabled", "Disabled". + :type infrastructure_encryption: str or + ~azure.mgmt.rdbms.postgresql.models.InfrastructureEncryption + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param create_mode: Required. The mode to create a new server.Constant filled by server. + Possible values include: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql.models.CreateMode + :param source_server_id: Required. The source server id to restore from. + :type source_server_id: str + :param restore_point_in_time: Required. Restore point creation time (ISO8601 format), + specifying the time to restore from. + :type restore_point_in_time: ~datetime.datetime + """ + + _validation = { + 'create_mode': {'required': True}, + 'source_server_id': {'required': True}, + 'restore_point_in_time': {'required': True}, + } + + _attribute_map = { + 'version': {'key': 'version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, + 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, + 'create_mode': {'key': 'createMode', 'type': 'str'}, + 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + 'restore_point_in_time': {'key': 'restorePointInTime', 'type': 'iso-8601'}, + } + + def __init__( + self, + *, + source_server_id: str, + restore_point_in_time: datetime.datetime, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + infrastructure_encryption: Optional[Union[str, "InfrastructureEncryption"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + storage_profile: Optional["StorageProfile"] = None, + **kwargs + ): + super(ServerPropertiesForRestore, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) + self.create_mode = 'PointInTimeRestore' # type: str + self.source_server_id = source_server_id + self.restore_point_in_time = restore_point_in_time + + +class ServerSecurityAlertPolicy(ProxyResource): + """A server security alert policy. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param state: Specifies the state of the policy, whether it is enabled or disabled. Possible + values include: "Enabled", "Disabled". + :type state: str or ~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicyState + :param disabled_alerts: Specifies an array of alerts that are disabled. Allowed values are: + Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly. + :type disabled_alerts: list[str] + :param email_addresses: Specifies an array of e-mail addresses to which the alert is sent. + :type email_addresses: list[str] + :param email_account_admins: Specifies that the alert is sent to the account administrators. + :type email_account_admins: bool + :param storage_endpoint: Specifies the blob storage endpoint (e.g. + https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection + audit logs. + :type storage_endpoint: str + :param storage_account_access_key: Specifies the identifier key of the Threat Detection audit + storage account. + :type storage_account_access_key: str + :param retention_days: Specifies the number of days to keep in the Threat Detection audit logs. + :type retention_days: int + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + 'disabled_alerts': {'key': 'properties.disabledAlerts', 'type': '[str]'}, + 'email_addresses': {'key': 'properties.emailAddresses', 'type': '[str]'}, + 'email_account_admins': {'key': 'properties.emailAccountAdmins', 'type': 'bool'}, + 'storage_endpoint': {'key': 'properties.storageEndpoint', 'type': 'str'}, + 'storage_account_access_key': {'key': 'properties.storageAccountAccessKey', 'type': 'str'}, + 'retention_days': {'key': 'properties.retentionDays', 'type': 'int'}, + } + + def __init__( + self, + *, + state: Optional[Union[str, "ServerSecurityAlertPolicyState"]] = None, + disabled_alerts: Optional[List[str]] = None, + email_addresses: Optional[List[str]] = None, + email_account_admins: Optional[bool] = None, + storage_endpoint: Optional[str] = None, + storage_account_access_key: Optional[str] = None, + retention_days: Optional[int] = None, + **kwargs + ): + super(ServerSecurityAlertPolicy, self).__init__(**kwargs) + self.state = state + self.disabled_alerts = disabled_alerts + self.email_addresses = email_addresses + self.email_account_admins = email_account_admins + self.storage_endpoint = storage_endpoint + self.storage_account_access_key = storage_account_access_key + self.retention_days = retention_days + + +class ServerSecurityAlertPolicyListResult(msrest.serialization.Model): + """A list of the server's security alert policies. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicy] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ServerSecurityAlertPolicy]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerSecurityAlertPolicyListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ServerUpdateParameters(msrest.serialization.Model): + """Parameters allowed to update for a server. + + :param identity: The Azure Active Directory identity of the server. + :type identity: ~azure.mgmt.rdbms.postgresql.models.ResourceIdentity + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.postgresql.models.Sku + :param tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :type tags: dict[str, str] + :param storage_profile: Storage profile of a server. + :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile + :param administrator_login_password: The password of the administrator login. + :type administrator_login_password: str + :param version: The version of a server. Possible values include: "9.5", "9.6", "10", "10.0", + "10.2", "11". + :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion + :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values + include: "Enabled", "Disabled". + :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum + :param minimal_tls_version: Enforce a minimal Tls version for the server. Possible values + include: "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + :type minimal_tls_version: str or ~azure.mgmt.rdbms.postgresql.models.MinimalTlsVersionEnum + :param public_network_access: Whether or not public network access is allowed for this server. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: + "Enabled", "Disabled". + :type public_network_access: str or ~azure.mgmt.rdbms.postgresql.models.PublicNetworkAccessEnum + :param replication_role: The replication role of the server. + :type replication_role: str + """ + + _attribute_map = { + 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, + 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, + 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, + 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, + 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + } + + def __init__( + self, + *, + identity: Optional["ResourceIdentity"] = None, + sku: Optional["Sku"] = None, + tags: Optional[Dict[str, str]] = None, + storage_profile: Optional["StorageProfile"] = None, + administrator_login_password: Optional[str] = None, + version: Optional[Union[str, "ServerVersion"]] = None, + ssl_enforcement: Optional[Union[str, "SslEnforcementEnum"]] = None, + minimal_tls_version: Optional[Union[str, "MinimalTlsVersionEnum"]] = None, + public_network_access: Optional[Union[str, "PublicNetworkAccessEnum"]] = None, + replication_role: Optional[str] = None, + **kwargs + ): + super(ServerUpdateParameters, self).__init__(**kwargs) + self.identity = identity + self.sku = sku + self.tags = tags + self.storage_profile = storage_profile + self.administrator_login_password = administrator_login_password + self.version = version + self.ssl_enforcement = ssl_enforcement + self.minimal_tls_version = minimal_tls_version + self.public_network_access = public_network_access + self.replication_role = replication_role + + +class Sku(msrest.serialization.Model): + """Billing information related properties of a server. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, + GP_Gen5_8. + :type name: str + :param tier: The tier of the particular SKU, e.g. Basic. Possible values include: "Basic", + "GeneralPurpose", "MemoryOptimized". + :type tier: str or ~azure.mgmt.rdbms.postgresql.models.SkuTier + :param capacity: The scale up/out capacity, representing server's compute units. + :type capacity: int + :param size: The size code, to be interpreted by resource as appropriate. + :type size: str + :param family: The family of hardware. + :type family: str + """ + + _validation = { + 'name': {'required': True}, + 'capacity': {'minimum': 0}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'tier': {'key': 'tier', 'type': 'str'}, + 'capacity': {'key': 'capacity', 'type': 'int'}, + 'size': {'key': 'size', 'type': 'str'}, + 'family': {'key': 'family', 'type': 'str'}, + } + + def __init__( + self, + *, + name: str, + tier: Optional[Union[str, "SkuTier"]] = None, + capacity: Optional[int] = None, + size: Optional[str] = None, + family: Optional[str] = None, + **kwargs + ): + super(Sku, self).__init__(**kwargs) + self.name = name + self.tier = tier + self.capacity = capacity + self.size = size + self.family = family + + +class StorageProfile(msrest.serialization.Model): + """Storage Profile properties of a server. + + :param backup_retention_days: Backup retention days for the server. + :type backup_retention_days: int + :param geo_redundant_backup: Enable Geo-redundant or not for server backup. Possible values + include: "Enabled", "Disabled". + :type geo_redundant_backup: str or ~azure.mgmt.rdbms.postgresql.models.GeoRedundantBackup + :param storage_mb: Max storage allowed for a server. + :type storage_mb: int + :param storage_autogrow: Enable Storage Auto Grow. Possible values include: "Enabled", + "Disabled". + :type storage_autogrow: str or ~azure.mgmt.rdbms.postgresql.models.StorageAutogrow + """ + + _attribute_map = { + 'backup_retention_days': {'key': 'backupRetentionDays', 'type': 'int'}, + 'geo_redundant_backup': {'key': 'geoRedundantBackup', 'type': 'str'}, + 'storage_mb': {'key': 'storageMB', 'type': 'int'}, + 'storage_autogrow': {'key': 'storageAutogrow', 'type': 'str'}, + } + + def __init__( + self, + *, + backup_retention_days: Optional[int] = None, + geo_redundant_backup: Optional[Union[str, "GeoRedundantBackup"]] = None, + storage_mb: Optional[int] = None, + storage_autogrow: Optional[Union[str, "StorageAutogrow"]] = None, + **kwargs + ): + super(StorageProfile, self).__init__(**kwargs) + self.backup_retention_days = backup_retention_days + self.geo_redundant_backup = geo_redundant_backup + self.storage_mb = storage_mb + self.storage_autogrow = storage_autogrow + + +class TagsObject(msrest.serialization.Model): + """Tags object for patch operations. + + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + """ + + _attribute_map = { + 'tags': {'key': 'tags', 'type': '{str}'}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + **kwargs + ): + super(TagsObject, self).__init__(**kwargs) + self.tags = tags + + +class VirtualNetworkRule(ProxyResource): + """A virtual network rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param virtual_network_subnet_id: The ARM resource id of the virtual network subnet. + :type virtual_network_subnet_id: str + :param ignore_missing_vnet_service_endpoint: Create firewall rule before the virtual network + has vnet service endpoint enabled. + :type ignore_missing_vnet_service_endpoint: bool + :ivar state: Virtual Network Rule State. Possible values include: "Initializing", "InProgress", + "Ready", "Deleting", "Unknown". + :vartype state: str or ~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRuleState + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'state': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'virtual_network_subnet_id': {'key': 'properties.virtualNetworkSubnetId', 'type': 'str'}, + 'ignore_missing_vnet_service_endpoint': {'key': 'properties.ignoreMissingVnetServiceEndpoint', 'type': 'bool'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + } + + def __init__( + self, + *, + virtual_network_subnet_id: Optional[str] = None, + ignore_missing_vnet_service_endpoint: Optional[bool] = None, + **kwargs + ): + super(VirtualNetworkRule, self).__init__(**kwargs) + self.virtual_network_subnet_id = virtual_network_subnet_id + self.ignore_missing_vnet_service_endpoint = ignore_missing_vnet_service_endpoint + self.state = None + + +class VirtualNetworkRuleListResult(msrest.serialization.Model): + """A list of virtual network rules. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: Array of results. + :vartype value: list[~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRule] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[VirtualNetworkRule]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(VirtualNetworkRuleListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/_postgre_sql_management_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/_postgre_sql_management_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..75c70a1f5abb5cefab67df36ee9edba297aa4ea4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/models/_postgre_sql_management_client_enums.py @@ -0,0 +1,180 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum, EnumMeta +from six import with_metaclass + +class _CaseInsensitiveEnumMeta(EnumMeta): + def __getitem__(self, name): + return super().__getitem__(name.upper()) + + def __getattr__(cls, name): + """Return the enum member matching `name` + We use __getattr__ instead of descriptors or inserting into the enum + class' __dict__ in order to support `name` and `value` being both + properties for enum members (which live in the class' __dict__) and + enum members themselves. + """ + try: + return cls._member_map_[name.upper()] + except KeyError: + raise AttributeError(name) + + +class CreateMode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The mode to create a new server. + """ + + DEFAULT = "Default" + POINT_IN_TIME_RESTORE = "PointInTimeRestore" + GEO_RESTORE = "GeoRestore" + REPLICA = "Replica" + +class GeoRedundantBackup(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Enable Geo-redundant or not for server backup. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class IdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an + Azure Active Directory principal for the resource. + """ + + SYSTEM_ASSIGNED = "SystemAssigned" + +class InfrastructureEncryption(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Add a second layer of encryption for your data using new encryption algorithm which gives + additional data protection. Value is optional but if passed in, must be 'Disabled' or + 'Enabled'. + """ + + #: Default value for single layer of encryption for data at rest. + ENABLED = "Enabled" + #: Additional (2nd) layer of encryption for data at rest. + DISABLED = "Disabled" + +class MinimalTlsVersionEnum(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Enforce a minimal Tls version for the server. + """ + + TLS1_0 = "TLS1_0" + TLS1_1 = "TLS1_1" + TLS1_2 = "TLS1_2" + TLS_ENFORCEMENT_DISABLED = "TLSEnforcementDisabled" + +class OperationOrigin(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The intended executor of the operation. + """ + + NOT_SPECIFIED = "NotSpecified" + USER = "user" + SYSTEM = "system" + +class PrivateEndpointProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """State of the private endpoint connection. + """ + + APPROVING = "Approving" + READY = "Ready" + DROPPING = "Dropping" + FAILED = "Failed" + REJECTING = "Rejecting" + +class PrivateLinkServiceConnectionStateActionsRequire(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The actions required for private link service connection. + """ + + NONE = "None" + +class PrivateLinkServiceConnectionStateStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The private link service connection status. + """ + + APPROVED = "Approved" + PENDING = "Pending" + REJECTED = "Rejected" + DISCONNECTED = "Disconnected" + +class PublicNetworkAccessEnum(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Whether or not public network access is allowed for this server. Value is optional but if + passed in, must be 'Enabled' or 'Disabled' + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class SecurityAlertPolicyName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + DEFAULT = "Default" + +class ServerKeyType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The key type like 'AzureKeyVault'. + """ + + AZURE_KEY_VAULT = "AzureKeyVault" + +class ServerSecurityAlertPolicyState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Specifies the state of the policy, whether it is enabled or disabled. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class ServerState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """A state of a server that is visible to user. + """ + + READY = "Ready" + DROPPING = "Dropping" + DISABLED = "Disabled" + INACCESSIBLE = "Inaccessible" + +class ServerVersion(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The version of a server. + """ + + NINE5 = "9.5" + NINE6 = "9.6" + TEN = "10" + TEN0 = "10.0" + TEN2 = "10.2" + ELEVEN = "11" + +class SkuTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The tier of the particular SKU, e.g. Basic. + """ + + BASIC = "Basic" + GENERAL_PURPOSE = "GeneralPurpose" + MEMORY_OPTIMIZED = "MemoryOptimized" + +class SslEnforcementEnum(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Enable ssl enforcement or not when connect to server. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class StorageAutogrow(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Enable Storage Auto Grow. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class VirtualNetworkRuleState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Virtual Network Rule State + """ + + INITIALIZING = "Initializing" + IN_PROGRESS = "InProgress" + READY = "Ready" + DELETING = "Deleting" + UNKNOWN = "Unknown" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..170155b069412ade542856e233092d994128b7b8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/__init__.py @@ -0,0 +1,47 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._servers_operations import ServersOperations +from ._replicas_operations import ReplicasOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._virtual_network_rules_operations import VirtualNetworkRulesOperations +from ._databases_operations import DatabasesOperations +from ._configurations_operations import ConfigurationsOperations +from ._server_parameters_operations import ServerParametersOperations +from ._log_files_operations import LogFilesOperations +from ._server_administrators_operations import ServerAdministratorsOperations +from ._recoverable_servers_operations import RecoverableServersOperations +from ._server_based_performance_tier_operations import ServerBasedPerformanceTierOperations +from ._location_based_performance_tier_operations import LocationBasedPerformanceTierOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._operations import Operations +from ._server_security_alert_policies_operations import ServerSecurityAlertPoliciesOperations +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._private_link_resources_operations import PrivateLinkResourcesOperations +from ._server_keys_operations import ServerKeysOperations + +__all__ = [ + 'ServersOperations', + 'ReplicasOperations', + 'FirewallRulesOperations', + 'VirtualNetworkRulesOperations', + 'DatabasesOperations', + 'ConfigurationsOperations', + 'ServerParametersOperations', + 'LogFilesOperations', + 'ServerAdministratorsOperations', + 'RecoverableServersOperations', + 'ServerBasedPerformanceTierOperations', + 'LocationBasedPerformanceTierOperations', + 'CheckNameAvailabilityOperations', + 'Operations', + 'ServerSecurityAlertPoliciesOperations', + 'PrivateEndpointConnectionsOperations', + 'PrivateLinkResourcesOperations', + 'ServerKeysOperations', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_check_name_availability_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_check_name_availability_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..afaffb94e85dd3cb49abedaa19c228723e81b686 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_check_name_availability_operations.py @@ -0,0 +1,105 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class CheckNameAvailabilityOperations(object): + """CheckNameAvailabilityOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def execute( + self, + name_availability_request, # type: "_models.NameAvailabilityRequest" + **kwargs # type: Any + ): + # type: (...) -> "_models.NameAvailability" + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. + :type name_availability_request: ~azure.mgmt.rdbms.postgresql.models.NameAvailabilityRequest + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.NameAvailability + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.execute.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('NameAvailability', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_configurations_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_configurations_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..706502c8a9015ceb31cd945c192998b7afec6de6 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_configurations_operations.py @@ -0,0 +1,321 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ConfigurationsOperations(object): + """ConfigurationsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + configuration_name, # type: str + parameters, # type: "_models.Configuration" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Configuration"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Configuration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + configuration_name, # type: str + parameters, # type: "_models.Configuration" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Configuration"] + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Configuration or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.Configuration" + """Gets information about a configuration of server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Configuration, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.Configuration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ConfigurationListResult"] + """List all the configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConfigurationListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_databases_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_databases_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..df1ce3383f361ba9bee91b0d90a1f5ce8c0ab3db --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_databases_operations.py @@ -0,0 +1,441 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class DatabasesOperations(object): + """DatabasesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + parameters, # type: "_models.Database" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Database"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Database"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Database') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Database', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + parameters, # type: "_models.Database" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Database"] + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.Database + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Database or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.Database" + """Gets information about a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Database, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.Database + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.DatabaseListResult"] + """List all the databases in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DatabaseListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.DatabaseListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.DatabaseListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('DatabaseListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_firewall_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_firewall_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d72f332cd5f193cf1cd9e68dc8cf376a1e699355 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_firewall_rules_operations.py @@ -0,0 +1,441 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class FirewallRulesOperations(object): + """FirewallRulesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + parameters, # type: "_models.FirewallRule" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.FirewallRule"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FirewallRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'FirewallRule') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + parameters, # type: "_models.FirewallRule" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.FirewallRule"] + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.FirewallRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either FirewallRule or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.FirewallRule" + """Gets information about a server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FirewallRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.FirewallRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.FirewallRuleListResult"] + """List all the firewall rules in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FirewallRuleListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.FirewallRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('FirewallRuleListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_location_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_location_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..e14bda10311d2e8057ee11b131f2030319684c89 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_location_based_performance_tier_operations.py @@ -0,0 +1,117 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedPerformanceTierOperations(object): + """LocationBasedPerformanceTierOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + location_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.PerformanceTierListResult"] + """List all the performance tiers at specified location in a given subscription. + + :param location_name: The name of the location. + :type location_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('PerformanceTierListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_log_files_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_log_files_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..771267843351861b8ca5551215eb4aab291718db --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_log_files_operations.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class LogFilesOperations(object): + """LogFilesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.LogFileListResult"] + """List all the log files in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either LogFileListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.LogFileListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.LogFileListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('LogFileListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/logFiles'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..190e2c6b2b5eb106008d23362d6706591d9d2c1a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_operations.py @@ -0,0 +1,92 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class Operations(object): + """Operations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> "_models.OperationListResult" + """Lists all of the available REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationListResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.OperationListResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.list.metadata['url'] # type: ignore + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + list.metadata = {'url': '/providers/Microsoft.DBforPostgreSQL/operations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_private_endpoint_connections_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_private_endpoint_connections_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..044d6a1dee75d2f08ecf4fa1bc590a794bae6797 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_private_endpoint_connections_operations.py @@ -0,0 +1,574 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class PrivateEndpointConnectionsOperations(object): + """PrivateEndpointConnectionsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.PrivateEndpointConnection" + """Gets a private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnection + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + parameters, # type: "_models.PrivateEndpointConnection" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.PrivateEndpointConnection"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.PrivateEndpointConnection"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'PrivateEndpointConnection') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + parameters, # type: "_models.PrivateEndpointConnection" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.PrivateEndpointConnection"] + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: + :type parameters: ~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnection + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def _update_tags_initial( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + parameters, # type: "_models.TagsObject" + **kwargs # type: Any + ): + # type: (...) -> "_models.PrivateEndpointConnection" + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_tags_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'TagsObject') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_tags_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def begin_update_tags( + self, + resource_group_name, # type: str + server_name, # type: str + private_endpoint_connection_name, # type: str + parameters, # type: "_models.TagsObject" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.PrivateEndpointConnection"] + """Updates tags on private endpoint connection. + + Updates private endpoint connection with the specified tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param private_endpoint_connection_name: + :type private_endpoint_connection_name: str + :param parameters: Parameters supplied to the Update private endpoint connection Tags + operation. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.TagsObject + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._update_tags_initial( + resource_group_name=resource_group_name, + server_name=server_name, + private_endpoint_connection_name=private_endpoint_connection_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.PrivateEndpointConnectionListResult"] + """Gets all private endpoint connections on a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateEndpointConnectionListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnectionListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('PrivateEndpointConnectionListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_private_link_resources_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_private_link_resources_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..08154faf43784456fb5b01ce67a3050bd014f203 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_private_link_resources_operations.py @@ -0,0 +1,184 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class PrivateLinkResourcesOperations(object): + """PrivateLinkResourcesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.PrivateLinkResourceListResult"] + """Gets the private link resources for PostgreSQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PrivateLinkResourceListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.PrivateLinkResourceListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('PrivateLinkResourceListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateLinkResources'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + group_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.PrivateLinkResource" + """Gets a private link resource for PostgreSQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param group_name: The name of the private link resource. + :type group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateLinkResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.PrivateLinkResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2018-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'groupName': self._serialize.url("group_name", group_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('PrivateLinkResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateLinkResources/{groupName}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_recoverable_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_recoverable_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..9d37cff94ad53d6e8b54857f2cc8ee4c27f29147 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_recoverable_servers_operations.py @@ -0,0 +1,104 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class RecoverableServersOperations(object): + """RecoverableServersOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.RecoverableServerResource" + """Gets a recoverable PostgreSQL Server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RecoverableServerResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.RecoverableServerResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.RecoverableServerResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('RecoverableServerResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/recoverableServers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_replicas_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_replicas_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..9220dbfa466cc2605f1c3e862e66b87b40f57bba --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_replicas_operations.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ReplicasOperations(object): + """ReplicasOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerListResult"] + """List all the replicas for a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/replicas'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_administrators_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_administrators_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..995133f25618d3dce0e0a117feaca951514e0ee2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_administrators_operations.py @@ -0,0 +1,424 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ServerAdministratorsOperations(object): + """ServerAdministratorsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.ServerAdministratorResource" + """Gets information about a AAD server administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerAdministratorResource, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.ServerAdministratorResource + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + properties, # type: "_models.ServerAdministratorResource" + **kwargs # type: Any + ): + # type: (...) -> "_models.ServerAdministratorResource" + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(properties, 'ServerAdministratorResource') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + properties, # type: "_models.ServerAdministratorResource" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.ServerAdministratorResource"] + """Creates or update active directory administrator on an existing server. The update action will + overwrite the existing administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param properties: The required parameters for creating or updating an AAD server + administrator. + :type properties: ~azure.mgmt.rdbms.postgresql.models.ServerAdministratorResource + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either ServerAdministratorResource or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.ServerAdministratorResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResource"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + properties=properties, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes server active directory administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory'} # type: ignore + + def list( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerAdministratorResourceListResult"] + """Returns a list of server Administrators. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerAdministratorResourceListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerAdministratorResourceListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerAdministratorResourceListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerAdministratorResourceListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_based_performance_tier_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_based_performance_tier_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..a96ca28d0e98f76058ebf819fac14c7476faab98 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_based_performance_tier_operations.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ServerBasedPerformanceTierOperations(object): + """ServerBasedPerformanceTierOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.PerformanceTierListResult"] + """List all the performance tiers for a PostgreSQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PerformanceTierListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.PerformanceTierListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.PerformanceTierListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('PerformanceTierListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/performanceTiers'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_keys_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_keys_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..bc22c43b5fcc8302327adef5cfed17c7cf91cd41 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_keys_operations.py @@ -0,0 +1,440 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ServerKeysOperations(object): + """ServerKeysOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerKeyListResult"] + """Gets a list of Server keys. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerKeyListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerKeyListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKeyListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerKeyListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + key_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.ServerKey" + """Gets a PostgreSQL Server key. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the PostgreSQL Server key to be retrieved. + :type key_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerKey, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.ServerKey + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerKey', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + def _create_or_update_initial( + self, + server_name, # type: str + key_name, # type: str + resource_group_name, # type: str + parameters, # type: "_models.ServerKey" + **kwargs # type: Any + ): + # type: (...) -> "_models.ServerKey" + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerKey') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('ServerKey', pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize('ServerKey', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + def begin_create_or_update( + self, + server_name, # type: str + key_name, # type: str + resource_group_name, # type: str + parameters, # type: "_models.ServerKey" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.ServerKey"] + """Creates or updates a PostgreSQL Server key. + + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the PostgreSQL Server key to be operated on (updated or created). + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param parameters: The requested PostgreSQL Server key resource state. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.ServerKey + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either ServerKey or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.ServerKey] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerKey"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + server_name=server_name, + key_name=key_name, + resource_group_name=resource_group_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ServerKey', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + def _delete_initial( + self, + server_name, # type: str + key_name, # type: str + resource_group_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-01-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}'} # type: ignore + + def begin_delete( + self, + server_name, # type: str + key_name, # type: str + resource_group_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes the PostgreSQL Server key with the given name. + + :param server_name: The name of the server. + :type server_name: str + :param key_name: The name of the PostgreSQL Server key to be deleted. + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + server_name=server_name, + key_name=key_name, + resource_group_name=resource_group_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_parameters_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_parameters_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..7426e954ccd86ad659225fb99a2f133f64d1ff12 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_parameters_operations.py @@ -0,0 +1,175 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ServerParametersOperations(object): + """ServerParametersOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _list_update_configurations_initial( + self, + resource_group_name, # type: str + server_name, # type: str + value, # type: "_models.ConfigurationListResult" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.ConfigurationListResult"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ConfigurationListResult"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._list_update_configurations_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(value, 'ConfigurationListResult') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _list_update_configurations_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/updateConfigurations'} # type: ignore + + def begin_list_update_configurations( + self, + resource_group_name, # type: str + server_name, # type: str + value, # type: "_models.ConfigurationListResult" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.ConfigurationListResult"] + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param value: The parameters for updating a list of server configuration. + :type value: ~azure.mgmt.rdbms.postgresql.models.ConfigurationListResult + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either ConfigurationListResult or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._list_update_configurations_initial( + resource_group_name=resource_group_name, + server_name=server_name, + value=value, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_list_update_configurations.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/updateConfigurations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_security_alert_policies_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_security_alert_policies_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..c99f16adc4c8bfa3377cfc7f8ff1c9d63373b7cf --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_server_security_alert_policies_operations.py @@ -0,0 +1,321 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ServerSecurityAlertPoliciesOperations(object): + """ServerSecurityAlertPoliciesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + security_alert_policy_name, # type: Union[str, "_models.SecurityAlertPolicyName"] + **kwargs # type: Any + ): + # type: (...) -> "_models.ServerSecurityAlertPolicy" + """Get a server's security alert policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the security alert policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.postgresql.models.SecurityAlertPolicyName + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ServerSecurityAlertPolicy, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicy + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + security_alert_policy_name, # type: Union[str, "_models.SecurityAlertPolicyName"] + parameters, # type: "_models.ServerSecurityAlertPolicy" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.ServerSecurityAlertPolicy"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ServerSecurityAlertPolicy"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerSecurityAlertPolicy') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + security_alert_policy_name, # type: Union[str, "_models.SecurityAlertPolicyName"] + parameters, # type: "_models.ServerSecurityAlertPolicy" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.ServerSecurityAlertPolicy"] + """Creates or updates a threat detection policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param security_alert_policy_name: The name of the threat detection policy. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.postgresql.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicy + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either ServerSecurityAlertPolicy or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicy"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + security_alert_policy_name=security_alert_policy_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'securityAlertPolicyName': self._serialize.url("security_alert_policy_name", security_alert_policy_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerSecurityAlertPolicyListResult"] + """Get the server's threat detection policies. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerSecurityAlertPolicyListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicyListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerSecurityAlertPolicyListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerSecurityAlertPolicyListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..2b84f92783c4020afd7d9c83f7e6b6457a3ffa46 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_servers_operations.py @@ -0,0 +1,725 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ServersOperations(object): + """ServersOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_initial( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.ServerForCreate" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Server"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerForCreate') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + def begin_create( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.ServerForCreate" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Server"] + """Creates a new server, or will overwrite an existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.ServerForCreate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + def _update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.ServerUpdateParameters" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Server"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerUpdateParameters') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + def begin_update( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.ServerUpdateParameters" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Server"] + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.ServerUpdateParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.Server" + """Gets information about a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Server, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.Server + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}'} # type: ignore + + def list_by_resource_group( + self, + resource_group_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerListResult"] + """List all the servers in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_resource_group.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers'} # type: ignore + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerListResult"] + """List all the servers in a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/servers'} # type: ignore + + def _restart_initial( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self._restart_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/restart'} # type: ignore + + def begin_restart( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._restart_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/restart'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_virtual_network_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_virtual_network_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd1a6cb08a5924917f3cb1146c94ef6542a3519 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql/operations/_virtual_network_rules_operations.py @@ -0,0 +1,439 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class VirtualNetworkRulesOperations(object): + """VirtualNetworkRulesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + virtual_network_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.VirtualNetworkRule" + """Gets a virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + virtual_network_rule_name, # type: str + parameters, # type: "_models.VirtualNetworkRule" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.VirtualNetworkRule"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.VirtualNetworkRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'VirtualNetworkRule') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + virtual_network_rule_name, # type: str + parameters, # type: "_models.VirtualNetworkRule" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.VirtualNetworkRule"] + """Creates or updates an existing virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :param parameters: The requested virtual Network Rule Resource state. + :type parameters: ~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either VirtualNetworkRule or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + virtual_network_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + virtual_network_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes the virtual network rule with the given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. + :type virtual_network_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + virtual_network_rule_name=virtual_network_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'virtualNetworkRuleName': self._serialize.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.VirtualNetworkRuleListResult"] + """Gets a list of virtual network rules in a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either VirtualNetworkRuleListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.VirtualNetworkRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2017-12-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('VirtualNetworkRuleListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9941983794af3ff6fb87b27113dbff110e321bc9 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._postgre_sql_management_client import PostgreSQLManagementClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['PostgreSQLManagementClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..1c9f11b8401f83512645645c80aa85e75f5dbc1f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/_configuration.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import TokenCredential + + +class PostgreSQLManagementClientConfiguration(Configuration): + """Configuration for PostgreSQLManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(PostgreSQLManagementClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-06-01" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/_postgre_sql_management_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/_postgre_sql_management_client.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff330675ab9d9334e7df8bd22e765b507db3e37 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/_postgre_sql_management_client.py @@ -0,0 +1,129 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.mgmt.core import ARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + + from azure.core.credentials import TokenCredential + from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from ._configuration import PostgreSQLManagementClientConfiguration +from .operations import ServersOperations +from .operations import FirewallRulesOperations +from .operations import ConfigurationsOperations +from .operations import CheckNameAvailabilityOperations +from .operations import LocationBasedCapabilitiesOperations +from .operations import VirtualNetworkSubnetUsageOperations +from .operations import Operations +from .operations import DatabasesOperations +from .operations import GetPrivateDnsZoneSuffixOperations +from . import models + + +class PostgreSQLManagementClient(object): + """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure PostgreSQL resources including servers, databases, firewall rules, VNET rules, security alert policies, log files and configurations with new business model. + + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.postgresql_flexibleservers.operations.ServersOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.rdbms.postgresql_flexibleservers.operations.FirewallRulesOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: azure.mgmt.rdbms.postgresql_flexibleservers.operations.ConfigurationsOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: azure.mgmt.rdbms.postgresql_flexibleservers.operations.CheckNameAvailabilityOperations + :ivar location_based_capabilities: LocationBasedCapabilitiesOperations operations + :vartype location_based_capabilities: azure.mgmt.rdbms.postgresql_flexibleservers.operations.LocationBasedCapabilitiesOperations + :ivar virtual_network_subnet_usage: VirtualNetworkSubnetUsageOperations operations + :vartype virtual_network_subnet_usage: azure.mgmt.rdbms.postgresql_flexibleservers.operations.VirtualNetworkSubnetUsageOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.postgresql_flexibleservers.operations.Operations + :ivar databases: DatabasesOperations operations + :vartype databases: azure.mgmt.rdbms.postgresql_flexibleservers.operations.DatabasesOperations + :ivar get_private_dns_zone_suffix: GetPrivateDnsZoneSuffixOperations operations + :vartype get_private_dns_zone_suffix: azure.mgmt.rdbms.postgresql_flexibleservers.operations.GetPrivateDnsZoneSuffixOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + base_url=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> None + if not base_url: + base_url = 'https://management.azure.com' + self._config = PostgreSQLManagementClientConfiguration(credential, subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.servers = ServersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.check_name_availability = CheckNameAvailabilityOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_based_capabilities = LocationBasedCapabilitiesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.virtual_network_subnet_usage = VirtualNetworkSubnetUsageOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.get_private_dns_zone_suffix = GetPrivateDnsZoneSuffixOperations( + self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, http_request, **kwargs): + # type: (HttpRequest, Any) -> HttpResponse + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.HttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> PostgreSQLManagementClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..c1257f7f4e111146dae88528000dc4841f2ef2aa --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "10.1.0" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97665f586f8374051945812a833b9b54989f8874 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._postgre_sql_management_client import PostgreSQLManagementClient +__all__ = ['PostgreSQLManagementClient'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb42d0b1fc3ea0f2675be1f3cb1b8143342feac --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class PostgreSQLManagementClientConfiguration(Configuration): + """Configuration for PostgreSQLManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(PostgreSQLManagementClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-06-01" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_postgre_sql_management_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_postgre_sql_management_client.py new file mode 100644 index 0000000000000000000000000000000000000000..fa66d8f5af29bba5914d1d22405a30c197cde527 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_postgre_sql_management_client.py @@ -0,0 +1,122 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +from ._configuration import PostgreSQLManagementClientConfiguration +from .operations import ServersOperations +from .operations import FirewallRulesOperations +from .operations import ConfigurationsOperations +from .operations import CheckNameAvailabilityOperations +from .operations import LocationBasedCapabilitiesOperations +from .operations import VirtualNetworkSubnetUsageOperations +from .operations import Operations +from .operations import DatabasesOperations +from .operations import GetPrivateDnsZoneSuffixOperations +from .. import models + + +class PostgreSQLManagementClient(object): + """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure PostgreSQL resources including servers, databases, firewall rules, VNET rules, security alert policies, log files and configurations with new business model. + + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.ServersOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.FirewallRulesOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.ConfigurationsOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.CheckNameAvailabilityOperations + :ivar location_based_capabilities: LocationBasedCapabilitiesOperations operations + :vartype location_based_capabilities: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.LocationBasedCapabilitiesOperations + :ivar virtual_network_subnet_usage: VirtualNetworkSubnetUsageOperations operations + :vartype virtual_network_subnet_usage: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.VirtualNetworkSubnetUsageOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.Operations + :ivar databases: DatabasesOperations operations + :vartype databases: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.DatabasesOperations + :ivar get_private_dns_zone_suffix: GetPrivateDnsZoneSuffixOperations operations + :vartype get_private_dns_zone_suffix: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.GetPrivateDnsZoneSuffixOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + **kwargs: Any + ) -> None: + if not base_url: + base_url = 'https://management.azure.com' + self._config = PostgreSQLManagementClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.servers = ServersOperations( + self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.check_name_availability = CheckNameAvailabilityOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_based_capabilities = LocationBasedCapabilitiesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.virtual_network_subnet_usage = VirtualNetworkSubnetUsageOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.get_private_dns_zone_suffix = GetPrivateDnsZoneSuffixOperations( + self._client, self._config, self._serialize, self._deserialize) + + async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "PostgreSQLManagementClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d0788161037b77537d23b160907dc3839b15fffe --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._servers_operations import ServersOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._configurations_operations import ConfigurationsOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._location_based_capabilities_operations import LocationBasedCapabilitiesOperations +from ._virtual_network_subnet_usage_operations import VirtualNetworkSubnetUsageOperations +from ._operations import Operations +from ._databases_operations import DatabasesOperations +from ._get_private_dns_zone_suffix_operations import GetPrivateDnsZoneSuffixOperations + +__all__ = [ + 'ServersOperations', + 'FirewallRulesOperations', + 'ConfigurationsOperations', + 'CheckNameAvailabilityOperations', + 'LocationBasedCapabilitiesOperations', + 'VirtualNetworkSubnetUsageOperations', + 'Operations', + 'DatabasesOperations', + 'GetPrivateDnsZoneSuffixOperations', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_check_name_availability_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_check_name_availability_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d40944e34d40099359e04aa12abbc481ae2d83d7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_check_name_availability_operations.py @@ -0,0 +1,100 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class CheckNameAvailabilityOperations: + """CheckNameAvailabilityOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def execute( + self, + name_availability_request: "_models.NameAvailabilityRequest", + **kwargs: Any + ) -> "_models.NameAvailability": + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. + :type name_availability_request: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.NameAvailabilityRequest + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.NameAvailability + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.execute.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('NameAvailability', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_configurations_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_configurations_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..02c1d5246048207feb022acae0700e4b44197d7f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_configurations_operations.py @@ -0,0 +1,446 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ConfigurationsOperations: + """ConfigurationsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ConfigurationListResult"]: + """List all the configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConfigurationListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + **kwargs: Any + ) -> "_models.Configuration": + """Gets information about a configuration of server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Configuration, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + async def _update_initial( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> Optional["_models.Configuration"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Configuration') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + async def begin_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> AsyncLROPoller["_models.Configuration"]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Configuration or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + async def _put_initial( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> Optional["_models.Configuration"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._put_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Configuration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _put_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + async def begin_put( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: "_models.Configuration", + **kwargs: Any + ) -> AsyncLROPoller["_models.Configuration"]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Configuration or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._put_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_put.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_databases_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_databases_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..7558d5163cec12143ee08578f346b3d99f275dcc --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_databases_operations.py @@ -0,0 +1,431 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class DatabasesOperations: + """DatabasesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> Optional["_models.Database"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Database"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Database') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Database', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + async def begin_create( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: "_models.Database", + **kwargs: Any + ) -> AsyncLROPoller["_models.Database"]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Database + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Database or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + database_name: str, + **kwargs: Any + ) -> "_models.Database": + """Gets information about a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Database, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Database + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.DatabaseListResult"]: + """List all the databases in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DatabaseListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.DatabaseListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.DatabaseListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('DatabaseListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_firewall_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_firewall_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..1ccd1991a2ea0dc92cd7356cec997a03fff9bf20 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_firewall_rules_operations.py @@ -0,0 +1,431 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class FirewallRulesOperations: + """FirewallRulesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_or_update_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> Optional["_models.FirewallRule"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FirewallRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'FirewallRule') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: "_models.FirewallRule", + **kwargs: Any + ) -> AsyncLROPoller["_models.FirewallRule"]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.FirewallRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either FirewallRule or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a PostgreSQL server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + **kwargs: Any + ) -> "_models.FirewallRule": + """List all the firewall rules in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FirewallRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.FirewallRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def list_by_server( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.FirewallRuleListResult"]: + """List all the firewall rules in a given PostgreSQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FirewallRuleListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.FirewallRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('FirewallRuleListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..c43bcf7c7cca1c7c6f66ac9c9511e38f8ce99017 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py @@ -0,0 +1,87 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class GetPrivateDnsZoneSuffixOperations: + """GetPrivateDnsZoneSuffixOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def execute( + self, + **kwargs: Any + ) -> str: + """Get private DNS zone suffix in the cloud. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: str, or the result of cls(response) + :rtype: str + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType[str] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.execute.metadata['url'] # type: ignore + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('str', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + execute.metadata = {'url': '/providers/Microsoft.DBforPostgreSQL/getPrivateDnsZoneSuffix'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_location_based_capabilities_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_location_based_capabilities_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..361afd9a67b9d0072aaecb6c2146e1e0f1f2a8e8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_location_based_capabilities_operations.py @@ -0,0 +1,112 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedCapabilitiesOperations: + """LocationBasedCapabilitiesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def execute( + self, + location_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.CapabilitiesListResult"]: + """Get capabilities at specified location in a given subscription. + + :param location_name: The name of the location. + :type location_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either CapabilitiesListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.CapabilitiesListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.CapabilitiesListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.execute.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('CapabilitiesListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/capabilities'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..2a5879c1b9ca6e2277a6bd11693332569f31512e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_operations.py @@ -0,0 +1,87 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class Operations: + """Operations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def list( + self, + **kwargs: Any + ) -> "_models.OperationListResult": + """Lists all of the available REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationListResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.OperationListResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.list.metadata['url'] # type: ignore + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + list.metadata = {'url': '/providers/Microsoft.DBforPostgreSQL/operations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0b7f98baf39280e4d7883f9c8168a7db25fb48 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_servers_operations.py @@ -0,0 +1,939 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ServersOperations: + """ServersOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.Server", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Server') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + async def begin_create( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.Server", + **kwargs: Any + ) -> AsyncLROPoller["_models.Server"]: + """Creates a new server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Server + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + async def _update_initial( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForUpdate", + **kwargs: Any + ) -> Optional["_models.Server"]: + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerForUpdate') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + async def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: "_models.ServerForUpdate", + **kwargs: Any + ) -> AsyncLROPoller["_models.Server"]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerForUpdate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> "_models.Server": + """Gets information about a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Server, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Server + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + def list_by_resource_group( + self, + resource_group_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the servers in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_resource_group.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers'} # type: ignore + + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.ServerListResult"]: + """List all the servers in a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/flexibleServers'} # type: ignore + + async def _restart_initial( + self, + resource_group_name: str, + server_name: str, + parameters: Optional["_models.RestartParameter"] = None, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._restart_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + if parameters is not None: + body_content = self._serialize.body(parameters, 'RestartParameter') + else: + body_content = None + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/restart'} # type: ignore + + async def begin_restart( + self, + resource_group_name: str, + server_name: str, + parameters: Optional["_models.RestartParameter"] = None, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The parameters for restarting a server. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.RestartParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._restart_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/restart'} # type: ignore + + async def _start_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self._start_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/start'} # type: ignore + + async def begin_start( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Starts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._start_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/start'} # type: ignore + + async def _stop_initial( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self._stop_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _stop_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/stop'} # type: ignore + + async def begin_stop( + self, + resource_group_name: str, + server_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Stops a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._stop_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/stop'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_virtual_network_subnet_usage_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_virtual_network_subnet_usage_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..fb957e0762b3a17a313d79f0cc41dff8ed694d84 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_virtual_network_subnet_usage_operations.py @@ -0,0 +1,103 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class VirtualNetworkSubnetUsageOperations: + """VirtualNetworkSubnetUsageOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def execute( + self, + location_name: str, + parameters: "_models.VirtualNetworkSubnetUsageParameter", + **kwargs: Any + ) -> "_models.VirtualNetworkSubnetUsageResult": + """Get virtual network subnet usage for a given vNet resource id. + + :param location_name: The name of the location. + :type location_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.VirtualNetworkSubnetUsageParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkSubnetUsageResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.VirtualNetworkSubnetUsageResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkSubnetUsageResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.execute.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'VirtualNetworkSubnetUsageParameter') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('VirtualNetworkSubnetUsageResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/checkVirtualNetworkSubnetUsage'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..184130773e2b461c733648933543a1b0bb0a701a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/__init__.py @@ -0,0 +1,159 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import Backup + from ._models_py3 import CapabilitiesListResult + from ._models_py3 import CapabilityProperties + from ._models_py3 import Configuration + from ._models_py3 import ConfigurationListResult + from ._models_py3 import Database + from ._models_py3 import DatabaseListResult + from ._models_py3 import DelegatedSubnetUsage + from ._models_py3 import ErrorAdditionalInfo + from ._models_py3 import ErrorResponse + from ._models_py3 import FirewallRule + from ._models_py3 import FirewallRuleListResult + from ._models_py3 import FlexibleServerEditionCapability + from ._models_py3 import HighAvailability + from ._models_py3 import HyperscaleNodeEditionCapability + from ._models_py3 import MaintenanceWindow + from ._models_py3 import NameAvailability + from ._models_py3 import NameAvailabilityRequest + from ._models_py3 import Network + from ._models_py3 import NodeTypeCapability + from ._models_py3 import Operation + from ._models_py3 import OperationDisplay + from ._models_py3 import OperationListResult + from ._models_py3 import ProxyResource + from ._models_py3 import Resource + from ._models_py3 import RestartParameter + from ._models_py3 import Server + from ._models_py3 import ServerForUpdate + from ._models_py3 import ServerListResult + from ._models_py3 import ServerVersionCapability + from ._models_py3 import Sku + from ._models_py3 import Storage + from ._models_py3 import StorageEditionCapability + from ._models_py3 import StorageMBCapability + from ._models_py3 import SystemData + from ._models_py3 import TrackedResource + from ._models_py3 import VcoreCapability + from ._models_py3 import VirtualNetworkSubnetUsageParameter + from ._models_py3 import VirtualNetworkSubnetUsageResult +except (SyntaxError, ImportError): + from ._models import Backup # type: ignore + from ._models import CapabilitiesListResult # type: ignore + from ._models import CapabilityProperties # type: ignore + from ._models import Configuration # type: ignore + from ._models import ConfigurationListResult # type: ignore + from ._models import Database # type: ignore + from ._models import DatabaseListResult # type: ignore + from ._models import DelegatedSubnetUsage # type: ignore + from ._models import ErrorAdditionalInfo # type: ignore + from ._models import ErrorResponse # type: ignore + from ._models import FirewallRule # type: ignore + from ._models import FirewallRuleListResult # type: ignore + from ._models import FlexibleServerEditionCapability # type: ignore + from ._models import HighAvailability # type: ignore + from ._models import HyperscaleNodeEditionCapability # type: ignore + from ._models import MaintenanceWindow # type: ignore + from ._models import NameAvailability # type: ignore + from ._models import NameAvailabilityRequest # type: ignore + from ._models import Network # type: ignore + from ._models import NodeTypeCapability # type: ignore + from ._models import Operation # type: ignore + from ._models import OperationDisplay # type: ignore + from ._models import OperationListResult # type: ignore + from ._models import ProxyResource # type: ignore + from ._models import Resource # type: ignore + from ._models import RestartParameter # type: ignore + from ._models import Server # type: ignore + from ._models import ServerForUpdate # type: ignore + from ._models import ServerListResult # type: ignore + from ._models import ServerVersionCapability # type: ignore + from ._models import Sku # type: ignore + from ._models import Storage # type: ignore + from ._models import StorageEditionCapability # type: ignore + from ._models import StorageMBCapability # type: ignore + from ._models import SystemData # type: ignore + from ._models import TrackedResource # type: ignore + from ._models import VcoreCapability # type: ignore + from ._models import VirtualNetworkSubnetUsageParameter # type: ignore + from ._models import VirtualNetworkSubnetUsageResult # type: ignore + +from ._postgre_sql_management_client_enums import ( + ConfigurationDataType, + CreateMode, + CreateModeForUpdate, + CreatedByType, + FailoverMode, + GeoRedundantBackupEnum, + HighAvailabilityMode, + OperationOrigin, + ServerHAState, + ServerPublicNetworkAccessState, + ServerState, + ServerVersion, + SkuTier, +) + +__all__ = [ + 'Backup', + 'CapabilitiesListResult', + 'CapabilityProperties', + 'Configuration', + 'ConfigurationListResult', + 'Database', + 'DatabaseListResult', + 'DelegatedSubnetUsage', + 'ErrorAdditionalInfo', + 'ErrorResponse', + 'FirewallRule', + 'FirewallRuleListResult', + 'FlexibleServerEditionCapability', + 'HighAvailability', + 'HyperscaleNodeEditionCapability', + 'MaintenanceWindow', + 'NameAvailability', + 'NameAvailabilityRequest', + 'Network', + 'NodeTypeCapability', + 'Operation', + 'OperationDisplay', + 'OperationListResult', + 'ProxyResource', + 'Resource', + 'RestartParameter', + 'Server', + 'ServerForUpdate', + 'ServerListResult', + 'ServerVersionCapability', + 'Sku', + 'Storage', + 'StorageEditionCapability', + 'StorageMBCapability', + 'SystemData', + 'TrackedResource', + 'VcoreCapability', + 'VirtualNetworkSubnetUsageParameter', + 'VirtualNetworkSubnetUsageResult', + 'ConfigurationDataType', + 'CreateMode', + 'CreateModeForUpdate', + 'CreatedByType', + 'FailoverMode', + 'GeoRedundantBackupEnum', + 'HighAvailabilityMode', + 'OperationOrigin', + 'ServerHAState', + 'ServerPublicNetworkAccessState', + 'ServerState', + 'ServerVersion', + 'SkuTier', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/_models.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..9c9bdbcfd502a9c6b49a2fea6c4641066a1599bf --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/_models.py @@ -0,0 +1,1509 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import msrest.serialization + + +class Backup(msrest.serialization.Model): + """Backup properties of a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param backup_retention_days: Backup retention days for the server. + :type backup_retention_days: int + :param geo_redundant_backup: A value indicating whether Geo-Redundant backup is enabled on the + server. Possible values include: "Enabled", "Disabled". + :type geo_redundant_backup: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.GeoRedundantBackupEnum + :ivar earliest_restore_date: The earliest restore point time (ISO8601 format) for server. + :vartype earliest_restore_date: ~datetime.datetime + """ + + _validation = { + 'earliest_restore_date': {'readonly': True}, + } + + _attribute_map = { + 'backup_retention_days': {'key': 'backupRetentionDays', 'type': 'int'}, + 'geo_redundant_backup': {'key': 'geoRedundantBackup', 'type': 'str'}, + 'earliest_restore_date': {'key': 'earliestRestoreDate', 'type': 'iso-8601'}, + } + + def __init__( + self, + **kwargs + ): + super(Backup, self).__init__(**kwargs) + self.backup_retention_days = kwargs.get('backup_retention_days', None) + self.geo_redundant_backup = kwargs.get('geo_redundant_backup', None) + self.earliest_restore_date = None + + +class CapabilitiesListResult(msrest.serialization.Model): + """location capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: A list of supported capabilities. + :vartype value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.CapabilityProperties] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[CapabilityProperties]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(CapabilitiesListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class CapabilityProperties(msrest.serialization.Model): + """Location capabilities. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar zone: zone name. + :vartype zone: str + :ivar geo_backup_supported: A value indicating whether a new server in this region can have + geo-backups to paired region. + :vartype geo_backup_supported: bool + :ivar zone_redundant_ha_supported: A value indicating whether a new server in this region can + support multi zone HA. + :vartype zone_redundant_ha_supported: bool + :ivar zone_redundant_ha_and_geo_backup_supported: A value indicating whether a new server in + this region can have geo-backups to paired region. + :vartype zone_redundant_ha_and_geo_backup_supported: bool + :ivar supported_flexible_server_editions: + :vartype supported_flexible_server_editions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.FlexibleServerEditionCapability] + :ivar supported_hyperscale_node_editions: + :vartype supported_hyperscale_node_editions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.HyperscaleNodeEditionCapability] + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'zone': {'readonly': True}, + 'geo_backup_supported': {'readonly': True}, + 'zone_redundant_ha_supported': {'readonly': True}, + 'zone_redundant_ha_and_geo_backup_supported': {'readonly': True}, + 'supported_flexible_server_editions': {'readonly': True}, + 'supported_hyperscale_node_editions': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'zone': {'key': 'zone', 'type': 'str'}, + 'geo_backup_supported': {'key': 'geoBackupSupported', 'type': 'bool'}, + 'zone_redundant_ha_supported': {'key': 'zoneRedundantHaSupported', 'type': 'bool'}, + 'zone_redundant_ha_and_geo_backup_supported': {'key': 'zoneRedundantHaAndGeoBackupSupported', 'type': 'bool'}, + 'supported_flexible_server_editions': {'key': 'supportedFlexibleServerEditions', 'type': '[FlexibleServerEditionCapability]'}, + 'supported_hyperscale_node_editions': {'key': 'supportedHyperscaleNodeEditions', 'type': '[HyperscaleNodeEditionCapability]'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(CapabilityProperties, self).__init__(**kwargs) + self.zone = None + self.geo_backup_supported = None + self.zone_redundant_ha_supported = None + self.zone_redundant_ha_and_geo_backup_supported = None + self.supported_flexible_server_editions = None + self.supported_hyperscale_node_editions = None + self.status = None + + +class Resource(msrest.serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class Configuration(ProxyResource): + """Represents a Configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :param value: Value of the configuration. + :type value: str + :ivar description: Description of the configuration. + :vartype description: str + :ivar default_value: Default value of the configuration. + :vartype default_value: str + :ivar data_type: Data type of the configuration. Possible values include: "Boolean", "Numeric", + "Integer", "Enumeration". + :vartype data_type: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ConfigurationDataType + :ivar allowed_values: Allowed values of the configuration. + :vartype allowed_values: str + :param source: Source of the configuration. + :type source: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'description': {'readonly': True}, + 'default_value': {'readonly': True}, + 'data_type': {'readonly': True}, + 'allowed_values': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'value': {'key': 'properties.value', 'type': 'str'}, + 'description': {'key': 'properties.description', 'type': 'str'}, + 'default_value': {'key': 'properties.defaultValue', 'type': 'str'}, + 'data_type': {'key': 'properties.dataType', 'type': 'str'}, + 'allowed_values': {'key': 'properties.allowedValues', 'type': 'str'}, + 'source': {'key': 'properties.source', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Configuration, self).__init__(**kwargs) + self.system_data = None + self.value = kwargs.get('value', None) + self.description = None + self.default_value = None + self.data_type = None + self.allowed_values = None + self.source = kwargs.get('source', None) + + +class ConfigurationListResult(msrest.serialization.Model): + """A list of server configurations. + + :param value: The list of server configurations. + :type value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration] + :param next_link: The link used to get the next page of operations. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Configuration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ConfigurationListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = kwargs.get('next_link', None) + + +class Database(ProxyResource): + """Represents a Database. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :param charset: The charset of the database. + :type charset: str + :param collation: The collation of the database. + :type collation: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'charset': {'key': 'properties.charset', 'type': 'str'}, + 'collation': {'key': 'properties.collation', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Database, self).__init__(**kwargs) + self.system_data = None + self.charset = kwargs.get('charset', None) + self.collation = kwargs.get('collation', None) + + +class DatabaseListResult(msrest.serialization.Model): + """A List of databases. + + :param value: The list of databases housed in a server. + :type value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Database] + :param next_link: The link used to get the next page of databases. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Database]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(DatabaseListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = kwargs.get('next_link', None) + + +class DelegatedSubnetUsage(msrest.serialization.Model): + """Delegated subnet usage data. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar subnet_name: name of the subnet. + :vartype subnet_name: str + :ivar usage: Number of used delegated subnets. + :vartype usage: long + """ + + _validation = { + 'subnet_name': {'readonly': True}, + 'usage': {'readonly': True}, + } + + _attribute_map = { + 'subnet_name': {'key': 'subnetName', 'type': 'str'}, + 'usage': {'key': 'usage', 'type': 'long'}, + } + + def __init__( + self, + **kwargs + ): + super(DelegatedSubnetUsage, self).__init__(**kwargs) + self.subnet_name = None + self.usage = None + + +class ErrorAdditionalInfo(msrest.serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorResponse(msrest.serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ErrorAdditionalInfo] + """ + + _validation = { + 'code': {'readonly': True}, + 'message': {'readonly': True}, + 'target': {'readonly': True}, + 'details': {'readonly': True}, + 'additional_info': {'readonly': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'target': {'key': 'target', 'type': 'str'}, + 'details': {'key': 'details', 'type': '[ErrorResponse]'}, + 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class FirewallRule(ProxyResource): + """Represents a server firewall rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :param start_ip_address: Required. The start IP address of the server firewall rule. Must be + IPv4 format. + :type start_ip_address: str + :param end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 + format. + :type end_ip_address: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'start_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + 'end_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'start_ip_address': {'key': 'properties.startIpAddress', 'type': 'str'}, + 'end_ip_address': {'key': 'properties.endIpAddress', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FirewallRule, self).__init__(**kwargs) + self.system_data = None + self.start_ip_address = kwargs['start_ip_address'] + self.end_ip_address = kwargs['end_ip_address'] + + +class FirewallRuleListResult(msrest.serialization.Model): + """A list of firewall rules. + + :param value: The list of firewall rules in a server. + :type value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.FirewallRule] + :param next_link: The link used to get the next page of operations. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FirewallRule]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FirewallRuleListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = kwargs.get('next_link', None) + + +class FlexibleServerEditionCapability(msrest.serialization.Model): + """Flexible server edition capabilities. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: Server edition name. + :vartype name: str + :ivar supported_storage_editions: The list of editions supported by this server edition. + :vartype supported_storage_editions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.StorageEditionCapability] + :ivar supported_server_versions: The list of server versions supported by this server edition. + :vartype supported_server_versions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerVersionCapability] + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_storage_editions': {'readonly': True}, + 'supported_server_versions': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_storage_editions': {'key': 'supportedStorageEditions', 'type': '[StorageEditionCapability]'}, + 'supported_server_versions': {'key': 'supportedServerVersions', 'type': '[ServerVersionCapability]'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FlexibleServerEditionCapability, self).__init__(**kwargs) + self.name = None + self.supported_storage_editions = None + self.supported_server_versions = None + self.status = None + + +class HighAvailability(msrest.serialization.Model): + """High availability properties of a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param mode: The HA mode for the server. Possible values include: "Disabled", "ZoneRedundant". + :type mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.HighAvailabilityMode + :ivar state: A state of a HA server that is visible to user. Possible values include: + "NotEnabled", "CreatingStandby", "ReplicatingData", "FailingOver", "Healthy", + "RemovingStandby". + :vartype state: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerHAState + :param standby_availability_zone: availability zone information of the standby. + :type standby_availability_zone: str + """ + + _validation = { + 'state': {'readonly': True}, + } + + _attribute_map = { + 'mode': {'key': 'mode', 'type': 'str'}, + 'state': {'key': 'state', 'type': 'str'}, + 'standby_availability_zone': {'key': 'standbyAvailabilityZone', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(HighAvailability, self).__init__(**kwargs) + self.mode = kwargs.get('mode', None) + self.state = None + self.standby_availability_zone = kwargs.get('standby_availability_zone', None) + + +class HyperscaleNodeEditionCapability(msrest.serialization.Model): + """Hyperscale node edition capabilities. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: Server edition name. + :vartype name: str + :ivar supported_storage_editions: The list of editions supported by this server edition. + :vartype supported_storage_editions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.StorageEditionCapability] + :ivar supported_server_versions: The list of server versions supported by this server edition. + :vartype supported_server_versions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerVersionCapability] + :ivar supported_node_types: The list of Node Types supported by this server edition. + :vartype supported_node_types: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.NodeTypeCapability] + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_storage_editions': {'readonly': True}, + 'supported_server_versions': {'readonly': True}, + 'supported_node_types': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_storage_editions': {'key': 'supportedStorageEditions', 'type': '[StorageEditionCapability]'}, + 'supported_server_versions': {'key': 'supportedServerVersions', 'type': '[ServerVersionCapability]'}, + 'supported_node_types': {'key': 'supportedNodeTypes', 'type': '[NodeTypeCapability]'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(HyperscaleNodeEditionCapability, self).__init__(**kwargs) + self.name = None + self.supported_storage_editions = None + self.supported_server_versions = None + self.supported_node_types = None + self.status = None + + +class MaintenanceWindow(msrest.serialization.Model): + """Maintenance window properties of a server. + + :param custom_window: indicates whether custom window is enabled or disabled. + :type custom_window: str + :param start_hour: start hour for maintenance window. + :type start_hour: int + :param start_minute: start minute for maintenance window. + :type start_minute: int + :param day_of_week: day of week for maintenance window. + :type day_of_week: int + """ + + _attribute_map = { + 'custom_window': {'key': 'customWindow', 'type': 'str'}, + 'start_hour': {'key': 'startHour', 'type': 'int'}, + 'start_minute': {'key': 'startMinute', 'type': 'int'}, + 'day_of_week': {'key': 'dayOfWeek', 'type': 'int'}, + } + + def __init__( + self, + **kwargs + ): + super(MaintenanceWindow, self).__init__(**kwargs) + self.custom_window = kwargs.get('custom_window', None) + self.start_hour = kwargs.get('start_hour', None) + self.start_minute = kwargs.get('start_minute', None) + self.day_of_week = kwargs.get('day_of_week', None) + + +class NameAvailability(msrest.serialization.Model): + """Represents a resource name availability. + + :param message: Error Message. + :type message: str + :param name_available: Indicates whether the resource name is available. + :type name_available: bool + :param name: name of the PostgreSQL server. + :type name: str + :param type: type of the server. + :type type: str + """ + + _attribute_map = { + 'message': {'key': 'message', 'type': 'str'}, + 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(NameAvailability, self).__init__(**kwargs) + self.message = kwargs.get('message', None) + self.name_available = kwargs.get('name_available', None) + self.name = kwargs.get('name', None) + self.type = kwargs.get('type', None) + + +class NameAvailabilityRequest(msrest.serialization.Model): + """Request from client to check resource name availability. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. Resource name to verify. + :type name: str + :param type: Resource type used for verification. + :type type: str + """ + + _validation = { + 'name': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(NameAvailabilityRequest, self).__init__(**kwargs) + self.name = kwargs['name'] + self.type = kwargs.get('type', None) + + +class Network(msrest.serialization.Model): + """Network properties of a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar public_network_access: public network access is enabled or not. Possible values include: + "Enabled", "Disabled". + :vartype public_network_access: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerPublicNetworkAccessState + :param delegated_subnet_resource_id: delegated subnet arm resource id. + :type delegated_subnet_resource_id: str + :param private_dns_zone_arm_resource_id: private dns zone arm resource id. + :type private_dns_zone_arm_resource_id: str + """ + + _validation = { + 'public_network_access': {'readonly': True}, + } + + _attribute_map = { + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'delegated_subnet_resource_id': {'key': 'delegatedSubnetResourceId', 'type': 'str'}, + 'private_dns_zone_arm_resource_id': {'key': 'privateDnsZoneArmResourceId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Network, self).__init__(**kwargs) + self.public_network_access = None + self.delegated_subnet_resource_id = kwargs.get('delegated_subnet_resource_id', None) + self.private_dns_zone_arm_resource_id = kwargs.get('private_dns_zone_arm_resource_id', None) + + +class NodeTypeCapability(msrest.serialization.Model): + """node type capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: note type name. + :vartype name: str + :ivar node_type: note type. + :vartype node_type: str + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'node_type': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'node_type': {'key': 'nodeType', 'type': 'str'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(NodeTypeCapability, self).__init__(**kwargs) + self.name = None + self.node_type = None + self.status = None + + +class Operation(msrest.serialization.Model): + """REST API operation definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation being performed on this particular object. + :vartype name: str + :ivar display: The localized display information for this particular operation or action. + :vartype display: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.OperationDisplay + :param is_data_action: Indicates whether the operation is a data action. + :type is_data_action: bool + :ivar origin: The intended executor of the operation. Possible values include: "NotSpecified", + "user", "system". + :vartype origin: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.OperationOrigin + :ivar properties: Additional descriptions for the operation. + :vartype properties: dict[str, any] + """ + + _validation = { + 'name': {'readonly': True}, + 'display': {'readonly': True}, + 'origin': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'OperationDisplay'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{object}'}, + } + + def __init__( + self, + **kwargs + ): + super(Operation, self).__init__(**kwargs) + self.name = None + self.display = None + self.is_data_action = kwargs.get('is_data_action', None) + self.origin = None + self.properties = None + + +class OperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: Operation resource provider name. + :vartype provider: str + :ivar resource: Resource on which the operation is performed. + :vartype resource: str + :ivar operation: Localized friendly name for the operation. + :vartype operation: str + :ivar description: Operation description. + :vartype description: str + """ + + _validation = { + 'provider': {'readonly': True}, + 'resource': {'readonly': True}, + 'operation': {'readonly': True}, + 'description': {'readonly': True}, + } + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationDisplay, self).__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(msrest.serialization.Model): + """A list of resource provider operations. + + :param value: Collection of available operation details. + :type value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Operation] + :param next_link: URL client should use to fetch the next page (per server side paging). + It's null for now, added for future use. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Operation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = kwargs.get('next_link', None) + + +class RestartParameter(msrest.serialization.Model): + """Represents server restart parameters. + + :param restart_with_failover: Indicates whether to restart the server with failover. + :type restart_with_failover: bool + :param failover_mode: Failover mode. Possible values include: "PlannedFailover", + "ForcedFailover", "PlannedSwitchover", "ForcedSwitchover". + :type failover_mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.FailoverMode + """ + + _attribute_map = { + 'restart_with_failover': {'key': 'restartWithFailover', 'type': 'bool'}, + 'failover_mode': {'key': 'failoverMode', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RestartParameter, self).__init__(**kwargs) + self.restart_with_failover = kwargs.get('restart_with_failover', None) + self.failover_mode = kwargs.get('failover_mode', None) + + +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(TrackedResource, self).__init__(**kwargs) + self.tags = kwargs.get('tags', None) + self.location = kwargs['location'] + + +class Server(TrackedResource): + """Represents a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Sku + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :param administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). + :type administrator_login: str + :param administrator_login_password: The administrator login password (required for server + creation). + :type administrator_login_password: str + :param version: PostgreSQL Server version. Possible values include: "13", "12", "11". + :type version: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerVersion + :ivar minor_version: The minor version of the server. + :vartype minor_version: str + :ivar state: A state of a server that is visible to user. Possible values include: "Ready", + "Dropping", "Disabled", "Starting", "Stopping", "Stopped", "Updating". + :vartype state: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerState + :ivar fully_qualified_domain_name: The fully qualified domain name of a server. + :vartype fully_qualified_domain_name: str + :param storage: Storage properties of a server. + :type storage: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Storage + :param backup: Backup properties of a server. + :type backup: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Backup + :param network: Network properties of a server. + :type network: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Network + :param high_availability: High availability properties of a server. + :type high_availability: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.HighAvailability + :param maintenance_window: Maintenance window properties of a server. + :type maintenance_window: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.MaintenanceWindow + :param source_server_resource_id: The source server resource ID to restore from. It's required + when 'createMode' is 'PointInTimeRestore'. + :type source_server_resource_id: str + :param point_in_time_utc: Restore point creation time (ISO8601 format), specifying the time to + restore from. It's required when 'createMode' is 'PointInTimeRestore'. + :type point_in_time_utc: ~datetime.datetime + :param availability_zone: availability zone information of the server. + :type availability_zone: str + :param create_mode: The mode to create a new PostgreSQL server. Possible values include: + "Default", "Create", "Update", "PointInTimeRestore". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreateMode + :param tags_properties_tags: Application-specific metadata in the form of key-value pairs. + :type tags_properties_tags: dict[str, str] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + 'system_data': {'readonly': True}, + 'minor_version': {'readonly': True}, + 'state': {'readonly': True}, + 'fully_qualified_domain_name': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'administrator_login': {'key': 'properties.administratorLogin', 'type': 'str'}, + 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'minor_version': {'key': 'properties.minorVersion', 'type': 'str'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + 'fully_qualified_domain_name': {'key': 'properties.fullyQualifiedDomainName', 'type': 'str'}, + 'storage': {'key': 'properties.storage', 'type': 'Storage'}, + 'backup': {'key': 'properties.backup', 'type': 'Backup'}, + 'network': {'key': 'properties.network', 'type': 'Network'}, + 'high_availability': {'key': 'properties.highAvailability', 'type': 'HighAvailability'}, + 'maintenance_window': {'key': 'properties.maintenanceWindow', 'type': 'MaintenanceWindow'}, + 'source_server_resource_id': {'key': 'properties.sourceServerResourceId', 'type': 'str'}, + 'point_in_time_utc': {'key': 'properties.pointInTimeUTC', 'type': 'iso-8601'}, + 'availability_zone': {'key': 'properties.availabilityZone', 'type': 'str'}, + 'create_mode': {'key': 'properties.createMode', 'type': 'str'}, + 'tags_properties_tags': {'key': 'properties.tags', 'type': '{str}'}, + } + + def __init__( + self, + **kwargs + ): + super(Server, self).__init__(**kwargs) + self.sku = kwargs.get('sku', None) + self.system_data = None + self.administrator_login = kwargs.get('administrator_login', None) + self.administrator_login_password = kwargs.get('administrator_login_password', None) + self.version = kwargs.get('version', None) + self.minor_version = None + self.state = None + self.fully_qualified_domain_name = None + self.storage = kwargs.get('storage', None) + self.backup = kwargs.get('backup', None) + self.network = kwargs.get('network', None) + self.high_availability = kwargs.get('high_availability', None) + self.maintenance_window = kwargs.get('maintenance_window', None) + self.source_server_resource_id = kwargs.get('source_server_resource_id', None) + self.point_in_time_utc = kwargs.get('point_in_time_utc', None) + self.availability_zone = kwargs.get('availability_zone', None) + self.create_mode = kwargs.get('create_mode', None) + self.tags_properties_tags = kwargs.get('tags_properties_tags', None) + + +class ServerForUpdate(msrest.serialization.Model): + """Represents a server to be updated. + + :param location: The location the resource resides in. + :type location: str + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Sku + :param tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :type tags: dict[str, str] + :param administrator_login_password: The password of the administrator login. + :type administrator_login_password: str + :param storage: Storage properties of a server. + :type storage: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Storage + :param backup: Backup properties of a server. + :type backup: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Backup + :param high_availability: High availability properties of a server. + :type high_availability: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.HighAvailability + :param maintenance_window: Maintenance window properties of a server. + :type maintenance_window: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.MaintenanceWindow + :param create_mode: The mode to update a new PostgreSQL server. Possible values include: + "Default", "Update". + :type create_mode: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreateModeForUpdate + """ + + _attribute_map = { + 'location': {'key': 'location', 'type': 'str'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, + 'storage': {'key': 'properties.storage', 'type': 'Storage'}, + 'backup': {'key': 'properties.backup', 'type': 'Backup'}, + 'high_availability': {'key': 'properties.highAvailability', 'type': 'HighAvailability'}, + 'maintenance_window': {'key': 'properties.maintenanceWindow', 'type': 'MaintenanceWindow'}, + 'create_mode': {'key': 'properties.createMode', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerForUpdate, self).__init__(**kwargs) + self.location = kwargs.get('location', None) + self.sku = kwargs.get('sku', None) + self.tags = kwargs.get('tags', None) + self.administrator_login_password = kwargs.get('administrator_login_password', None) + self.storage = kwargs.get('storage', None) + self.backup = kwargs.get('backup', None) + self.high_availability = kwargs.get('high_availability', None) + self.maintenance_window = kwargs.get('maintenance_window', None) + self.create_mode = kwargs.get('create_mode', None) + + +class ServerListResult(msrest.serialization.Model): + """A list of servers. + + :param value: The list of flexible servers. + :type value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Server] + :param next_link: The link used to get the next page of operations. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Server]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = kwargs.get('next_link', None) + + +class ServerVersionCapability(msrest.serialization.Model): + """Server version capabilities. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: server version. + :vartype name: str + :ivar supported_vcores: + :vartype supported_vcores: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.VcoreCapability] + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_vcores': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_vcores': {'key': 'supportedVcores', 'type': '[VcoreCapability]'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerVersionCapability, self).__init__(**kwargs) + self.name = None + self.supported_vcores = None + self.status = None + + +class Sku(msrest.serialization.Model): + """Sku information related properties of a server. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. The name of the sku, typically, tier + family + cores, e.g. + Standard_D4s_v3. + :type name: str + :param tier: Required. The tier of the particular SKU, e.g. Burstable. Possible values include: + "Burstable", "GeneralPurpose", "MemoryOptimized". + :type tier: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SkuTier + """ + + _validation = { + 'name': {'required': True}, + 'tier': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'tier': {'key': 'tier', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Sku, self).__init__(**kwargs) + self.name = kwargs['name'] + self.tier = kwargs['tier'] + + +class Storage(msrest.serialization.Model): + """Storage properties of a server. + + :param storage_size_gb: Max storage allowed for a server. + :type storage_size_gb: int + """ + + _attribute_map = { + 'storage_size_gb': {'key': 'storageSizeGB', 'type': 'int'}, + } + + def __init__( + self, + **kwargs + ): + super(Storage, self).__init__(**kwargs) + self.storage_size_gb = kwargs.get('storage_size_gb', None) + + +class StorageEditionCapability(msrest.serialization.Model): + """storage edition capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: storage edition name. + :vartype name: str + :ivar supported_storage_mb: + :vartype supported_storage_mb: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.StorageMBCapability] + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_storage_mb': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_storage_mb': {'key': 'supportedStorageMB', 'type': '[StorageMBCapability]'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(StorageEditionCapability, self).__init__(**kwargs) + self.name = None + self.supported_storage_mb = None + self.status = None + + +class StorageMBCapability(msrest.serialization.Model): + """storage size in MB capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: storage MB name. + :vartype name: str + :ivar supported_iops: supported IOPS. + :vartype supported_iops: long + :ivar storage_size_mb: storage size in MB. + :vartype storage_size_mb: long + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_iops': {'readonly': True}, + 'storage_size_mb': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_iops': {'key': 'supportedIops', 'type': 'long'}, + 'storage_size_mb': {'key': 'storageSizeMB', 'type': 'long'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(StorageMBCapability, self).__init__(**kwargs) + self.name = None + self.supported_iops = None + self.storage_size_mb = None + self.status = None + + +class SystemData(msrest.serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :param created_by: The identity that created the resource. + :type created_by: str + :param created_by_type: The type of identity that created the resource. Possible values + include: "User", "Application", "ManagedIdentity", "Key". + :type created_by_type: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreatedByType + :param created_at: The timestamp of resource creation (UTC). + :type created_at: ~datetime.datetime + :param last_modified_by: The identity that last modified the resource. + :type last_modified_by: str + :param last_modified_by_type: The type of identity that last modified the resource. Possible + values include: "User", "Application", "ManagedIdentity", "Key". + :type last_modified_by_type: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreatedByType + :param last_modified_at: The timestamp of resource last modification (UTC). + :type last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + 'created_by': {'key': 'createdBy', 'type': 'str'}, + 'created_by_type': {'key': 'createdByType', 'type': 'str'}, + 'created_at': {'key': 'createdAt', 'type': 'iso-8601'}, + 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'str'}, + 'last_modified_by_type': {'key': 'lastModifiedByType', 'type': 'str'}, + 'last_modified_at': {'key': 'lastModifiedAt', 'type': 'iso-8601'}, + } + + def __init__( + self, + **kwargs + ): + super(SystemData, self).__init__(**kwargs) + self.created_by = kwargs.get('created_by', None) + self.created_by_type = kwargs.get('created_by_type', None) + self.created_at = kwargs.get('created_at', None) + self.last_modified_by = kwargs.get('last_modified_by', None) + self.last_modified_by_type = kwargs.get('last_modified_by_type', None) + self.last_modified_at = kwargs.get('last_modified_at', None) + + +class VcoreCapability(msrest.serialization.Model): + """Vcores capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: vCore name. + :vartype name: str + :ivar v_cores: supported vCores. + :vartype v_cores: long + :ivar supported_iops: supported IOPS. + :vartype supported_iops: long + :ivar supported_memory_per_vcore_mb: supported memory per vCore in MB. + :vartype supported_memory_per_vcore_mb: long + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'v_cores': {'readonly': True}, + 'supported_iops': {'readonly': True}, + 'supported_memory_per_vcore_mb': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'v_cores': {'key': 'vCores', 'type': 'long'}, + 'supported_iops': {'key': 'supportedIops', 'type': 'long'}, + 'supported_memory_per_vcore_mb': {'key': 'supportedMemoryPerVcoreMB', 'type': 'long'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(VcoreCapability, self).__init__(**kwargs) + self.name = None + self.v_cores = None + self.supported_iops = None + self.supported_memory_per_vcore_mb = None + self.status = None + + +class VirtualNetworkSubnetUsageParameter(msrest.serialization.Model): + """Virtual network subnet usage parameter. + + :param virtual_network_arm_resource_id: Virtual network resource id. + :type virtual_network_arm_resource_id: str + """ + + _attribute_map = { + 'virtual_network_arm_resource_id': {'key': 'virtualNetworkArmResourceId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(VirtualNetworkSubnetUsageParameter, self).__init__(**kwargs) + self.virtual_network_arm_resource_id = kwargs.get('virtual_network_arm_resource_id', None) + + +class VirtualNetworkSubnetUsageResult(msrest.serialization.Model): + """Virtual network subnet usage data. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar delegated_subnets_usage: + :vartype delegated_subnets_usage: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.DelegatedSubnetUsage] + """ + + _validation = { + 'delegated_subnets_usage': {'readonly': True}, + } + + _attribute_map = { + 'delegated_subnets_usage': {'key': 'delegatedSubnetsUsage', 'type': '[DelegatedSubnetUsage]'}, + } + + def __init__( + self, + **kwargs + ): + super(VirtualNetworkSubnetUsageResult, self).__init__(**kwargs) + self.delegated_subnets_usage = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef34c600f5a00155a0df0c1fd17bfa78d7a86e8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/_models_py3.py @@ -0,0 +1,1609 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import Dict, List, Optional, Union + +import msrest.serialization + +from ._postgre_sql_management_client_enums import * + + +class Backup(msrest.serialization.Model): + """Backup properties of a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param backup_retention_days: Backup retention days for the server. + :type backup_retention_days: int + :param geo_redundant_backup: A value indicating whether Geo-Redundant backup is enabled on the + server. Possible values include: "Enabled", "Disabled". + :type geo_redundant_backup: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.GeoRedundantBackupEnum + :ivar earliest_restore_date: The earliest restore point time (ISO8601 format) for server. + :vartype earliest_restore_date: ~datetime.datetime + """ + + _validation = { + 'earliest_restore_date': {'readonly': True}, + } + + _attribute_map = { + 'backup_retention_days': {'key': 'backupRetentionDays', 'type': 'int'}, + 'geo_redundant_backup': {'key': 'geoRedundantBackup', 'type': 'str'}, + 'earliest_restore_date': {'key': 'earliestRestoreDate', 'type': 'iso-8601'}, + } + + def __init__( + self, + *, + backup_retention_days: Optional[int] = None, + geo_redundant_backup: Optional[Union[str, "GeoRedundantBackupEnum"]] = None, + **kwargs + ): + super(Backup, self).__init__(**kwargs) + self.backup_retention_days = backup_retention_days + self.geo_redundant_backup = geo_redundant_backup + self.earliest_restore_date = None + + +class CapabilitiesListResult(msrest.serialization.Model): + """location capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: A list of supported capabilities. + :vartype value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.CapabilityProperties] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[CapabilityProperties]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(CapabilitiesListResult, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class CapabilityProperties(msrest.serialization.Model): + """Location capabilities. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar zone: zone name. + :vartype zone: str + :ivar geo_backup_supported: A value indicating whether a new server in this region can have + geo-backups to paired region. + :vartype geo_backup_supported: bool + :ivar zone_redundant_ha_supported: A value indicating whether a new server in this region can + support multi zone HA. + :vartype zone_redundant_ha_supported: bool + :ivar zone_redundant_ha_and_geo_backup_supported: A value indicating whether a new server in + this region can have geo-backups to paired region. + :vartype zone_redundant_ha_and_geo_backup_supported: bool + :ivar supported_flexible_server_editions: + :vartype supported_flexible_server_editions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.FlexibleServerEditionCapability] + :ivar supported_hyperscale_node_editions: + :vartype supported_hyperscale_node_editions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.HyperscaleNodeEditionCapability] + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'zone': {'readonly': True}, + 'geo_backup_supported': {'readonly': True}, + 'zone_redundant_ha_supported': {'readonly': True}, + 'zone_redundant_ha_and_geo_backup_supported': {'readonly': True}, + 'supported_flexible_server_editions': {'readonly': True}, + 'supported_hyperscale_node_editions': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'zone': {'key': 'zone', 'type': 'str'}, + 'geo_backup_supported': {'key': 'geoBackupSupported', 'type': 'bool'}, + 'zone_redundant_ha_supported': {'key': 'zoneRedundantHaSupported', 'type': 'bool'}, + 'zone_redundant_ha_and_geo_backup_supported': {'key': 'zoneRedundantHaAndGeoBackupSupported', 'type': 'bool'}, + 'supported_flexible_server_editions': {'key': 'supportedFlexibleServerEditions', 'type': '[FlexibleServerEditionCapability]'}, + 'supported_hyperscale_node_editions': {'key': 'supportedHyperscaleNodeEditions', 'type': '[HyperscaleNodeEditionCapability]'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(CapabilityProperties, self).__init__(**kwargs) + self.zone = None + self.geo_backup_supported = None + self.zone_redundant_ha_supported = None + self.zone_redundant_ha_and_geo_backup_supported = None + self.supported_flexible_server_editions = None + self.supported_hyperscale_node_editions = None + self.status = None + + +class Resource(msrest.serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class Configuration(ProxyResource): + """Represents a Configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :param value: Value of the configuration. + :type value: str + :ivar description: Description of the configuration. + :vartype description: str + :ivar default_value: Default value of the configuration. + :vartype default_value: str + :ivar data_type: Data type of the configuration. Possible values include: "Boolean", "Numeric", + "Integer", "Enumeration". + :vartype data_type: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ConfigurationDataType + :ivar allowed_values: Allowed values of the configuration. + :vartype allowed_values: str + :param source: Source of the configuration. + :type source: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'description': {'readonly': True}, + 'default_value': {'readonly': True}, + 'data_type': {'readonly': True}, + 'allowed_values': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'value': {'key': 'properties.value', 'type': 'str'}, + 'description': {'key': 'properties.description', 'type': 'str'}, + 'default_value': {'key': 'properties.defaultValue', 'type': 'str'}, + 'data_type': {'key': 'properties.dataType', 'type': 'str'}, + 'allowed_values': {'key': 'properties.allowedValues', 'type': 'str'}, + 'source': {'key': 'properties.source', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[str] = None, + source: Optional[str] = None, + **kwargs + ): + super(Configuration, self).__init__(**kwargs) + self.system_data = None + self.value = value + self.description = None + self.default_value = None + self.data_type = None + self.allowed_values = None + self.source = source + + +class ConfigurationListResult(msrest.serialization.Model): + """A list of server configurations. + + :param value: The list of server configurations. + :type value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration] + :param next_link: The link used to get the next page of operations. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Configuration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["Configuration"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + super(ConfigurationListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class Database(ProxyResource): + """Represents a Database. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :param charset: The charset of the database. + :type charset: str + :param collation: The collation of the database. + :type collation: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'charset': {'key': 'properties.charset', 'type': 'str'}, + 'collation': {'key': 'properties.collation', 'type': 'str'}, + } + + def __init__( + self, + *, + charset: Optional[str] = None, + collation: Optional[str] = None, + **kwargs + ): + super(Database, self).__init__(**kwargs) + self.system_data = None + self.charset = charset + self.collation = collation + + +class DatabaseListResult(msrest.serialization.Model): + """A List of databases. + + :param value: The list of databases housed in a server. + :type value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Database] + :param next_link: The link used to get the next page of databases. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Database]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["Database"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + super(DatabaseListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class DelegatedSubnetUsage(msrest.serialization.Model): + """Delegated subnet usage data. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar subnet_name: name of the subnet. + :vartype subnet_name: str + :ivar usage: Number of used delegated subnets. + :vartype usage: long + """ + + _validation = { + 'subnet_name': {'readonly': True}, + 'usage': {'readonly': True}, + } + + _attribute_map = { + 'subnet_name': {'key': 'subnetName', 'type': 'str'}, + 'usage': {'key': 'usage', 'type': 'long'}, + } + + def __init__( + self, + **kwargs + ): + super(DelegatedSubnetUsage, self).__init__(**kwargs) + self.subnet_name = None + self.usage = None + + +class ErrorAdditionalInfo(msrest.serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorResponse(msrest.serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ErrorAdditionalInfo] + """ + + _validation = { + 'code': {'readonly': True}, + 'message': {'readonly': True}, + 'target': {'readonly': True}, + 'details': {'readonly': True}, + 'additional_info': {'readonly': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'target': {'key': 'target', 'type': 'str'}, + 'details': {'key': 'details', 'type': '[ErrorResponse]'}, + 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class FirewallRule(ProxyResource): + """Represents a server firewall rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :param start_ip_address: Required. The start IP address of the server firewall rule. Must be + IPv4 format. + :type start_ip_address: str + :param end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 + format. + :type end_ip_address: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'start_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + 'end_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'start_ip_address': {'key': 'properties.startIpAddress', 'type': 'str'}, + 'end_ip_address': {'key': 'properties.endIpAddress', 'type': 'str'}, + } + + def __init__( + self, + *, + start_ip_address: str, + end_ip_address: str, + **kwargs + ): + super(FirewallRule, self).__init__(**kwargs) + self.system_data = None + self.start_ip_address = start_ip_address + self.end_ip_address = end_ip_address + + +class FirewallRuleListResult(msrest.serialization.Model): + """A list of firewall rules. + + :param value: The list of firewall rules in a server. + :type value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.FirewallRule] + :param next_link: The link used to get the next page of operations. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FirewallRule]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["FirewallRule"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + super(FirewallRuleListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class FlexibleServerEditionCapability(msrest.serialization.Model): + """Flexible server edition capabilities. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: Server edition name. + :vartype name: str + :ivar supported_storage_editions: The list of editions supported by this server edition. + :vartype supported_storage_editions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.StorageEditionCapability] + :ivar supported_server_versions: The list of server versions supported by this server edition. + :vartype supported_server_versions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerVersionCapability] + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_storage_editions': {'readonly': True}, + 'supported_server_versions': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_storage_editions': {'key': 'supportedStorageEditions', 'type': '[StorageEditionCapability]'}, + 'supported_server_versions': {'key': 'supportedServerVersions', 'type': '[ServerVersionCapability]'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FlexibleServerEditionCapability, self).__init__(**kwargs) + self.name = None + self.supported_storage_editions = None + self.supported_server_versions = None + self.status = None + + +class HighAvailability(msrest.serialization.Model): + """High availability properties of a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param mode: The HA mode for the server. Possible values include: "Disabled", "ZoneRedundant". + :type mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.HighAvailabilityMode + :ivar state: A state of a HA server that is visible to user. Possible values include: + "NotEnabled", "CreatingStandby", "ReplicatingData", "FailingOver", "Healthy", + "RemovingStandby". + :vartype state: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerHAState + :param standby_availability_zone: availability zone information of the standby. + :type standby_availability_zone: str + """ + + _validation = { + 'state': {'readonly': True}, + } + + _attribute_map = { + 'mode': {'key': 'mode', 'type': 'str'}, + 'state': {'key': 'state', 'type': 'str'}, + 'standby_availability_zone': {'key': 'standbyAvailabilityZone', 'type': 'str'}, + } + + def __init__( + self, + *, + mode: Optional[Union[str, "HighAvailabilityMode"]] = None, + standby_availability_zone: Optional[str] = None, + **kwargs + ): + super(HighAvailability, self).__init__(**kwargs) + self.mode = mode + self.state = None + self.standby_availability_zone = standby_availability_zone + + +class HyperscaleNodeEditionCapability(msrest.serialization.Model): + """Hyperscale node edition capabilities. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: Server edition name. + :vartype name: str + :ivar supported_storage_editions: The list of editions supported by this server edition. + :vartype supported_storage_editions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.StorageEditionCapability] + :ivar supported_server_versions: The list of server versions supported by this server edition. + :vartype supported_server_versions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerVersionCapability] + :ivar supported_node_types: The list of Node Types supported by this server edition. + :vartype supported_node_types: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.NodeTypeCapability] + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_storage_editions': {'readonly': True}, + 'supported_server_versions': {'readonly': True}, + 'supported_node_types': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_storage_editions': {'key': 'supportedStorageEditions', 'type': '[StorageEditionCapability]'}, + 'supported_server_versions': {'key': 'supportedServerVersions', 'type': '[ServerVersionCapability]'}, + 'supported_node_types': {'key': 'supportedNodeTypes', 'type': '[NodeTypeCapability]'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(HyperscaleNodeEditionCapability, self).__init__(**kwargs) + self.name = None + self.supported_storage_editions = None + self.supported_server_versions = None + self.supported_node_types = None + self.status = None + + +class MaintenanceWindow(msrest.serialization.Model): + """Maintenance window properties of a server. + + :param custom_window: indicates whether custom window is enabled or disabled. + :type custom_window: str + :param start_hour: start hour for maintenance window. + :type start_hour: int + :param start_minute: start minute for maintenance window. + :type start_minute: int + :param day_of_week: day of week for maintenance window. + :type day_of_week: int + """ + + _attribute_map = { + 'custom_window': {'key': 'customWindow', 'type': 'str'}, + 'start_hour': {'key': 'startHour', 'type': 'int'}, + 'start_minute': {'key': 'startMinute', 'type': 'int'}, + 'day_of_week': {'key': 'dayOfWeek', 'type': 'int'}, + } + + def __init__( + self, + *, + custom_window: Optional[str] = None, + start_hour: Optional[int] = None, + start_minute: Optional[int] = None, + day_of_week: Optional[int] = None, + **kwargs + ): + super(MaintenanceWindow, self).__init__(**kwargs) + self.custom_window = custom_window + self.start_hour = start_hour + self.start_minute = start_minute + self.day_of_week = day_of_week + + +class NameAvailability(msrest.serialization.Model): + """Represents a resource name availability. + + :param message: Error Message. + :type message: str + :param name_available: Indicates whether the resource name is available. + :type name_available: bool + :param name: name of the PostgreSQL server. + :type name: str + :param type: type of the server. + :type type: str + """ + + _attribute_map = { + 'message': {'key': 'message', 'type': 'str'}, + 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + message: Optional[str] = None, + name_available: Optional[bool] = None, + name: Optional[str] = None, + type: Optional[str] = None, + **kwargs + ): + super(NameAvailability, self).__init__(**kwargs) + self.message = message + self.name_available = name_available + self.name = name + self.type = type + + +class NameAvailabilityRequest(msrest.serialization.Model): + """Request from client to check resource name availability. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. Resource name to verify. + :type name: str + :param type: Resource type used for verification. + :type type: str + """ + + _validation = { + 'name': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + name: str, + type: Optional[str] = None, + **kwargs + ): + super(NameAvailabilityRequest, self).__init__(**kwargs) + self.name = name + self.type = type + + +class Network(msrest.serialization.Model): + """Network properties of a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar public_network_access: public network access is enabled or not. Possible values include: + "Enabled", "Disabled". + :vartype public_network_access: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerPublicNetworkAccessState + :param delegated_subnet_resource_id: delegated subnet arm resource id. + :type delegated_subnet_resource_id: str + :param private_dns_zone_arm_resource_id: private dns zone arm resource id. + :type private_dns_zone_arm_resource_id: str + """ + + _validation = { + 'public_network_access': {'readonly': True}, + } + + _attribute_map = { + 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, + 'delegated_subnet_resource_id': {'key': 'delegatedSubnetResourceId', 'type': 'str'}, + 'private_dns_zone_arm_resource_id': {'key': 'privateDnsZoneArmResourceId', 'type': 'str'}, + } + + def __init__( + self, + *, + delegated_subnet_resource_id: Optional[str] = None, + private_dns_zone_arm_resource_id: Optional[str] = None, + **kwargs + ): + super(Network, self).__init__(**kwargs) + self.public_network_access = None + self.delegated_subnet_resource_id = delegated_subnet_resource_id + self.private_dns_zone_arm_resource_id = private_dns_zone_arm_resource_id + + +class NodeTypeCapability(msrest.serialization.Model): + """node type capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: note type name. + :vartype name: str + :ivar node_type: note type. + :vartype node_type: str + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'node_type': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'node_type': {'key': 'nodeType', 'type': 'str'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(NodeTypeCapability, self).__init__(**kwargs) + self.name = None + self.node_type = None + self.status = None + + +class Operation(msrest.serialization.Model): + """REST API operation definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation being performed on this particular object. + :vartype name: str + :ivar display: The localized display information for this particular operation or action. + :vartype display: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.OperationDisplay + :param is_data_action: Indicates whether the operation is a data action. + :type is_data_action: bool + :ivar origin: The intended executor of the operation. Possible values include: "NotSpecified", + "user", "system". + :vartype origin: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.OperationOrigin + :ivar properties: Additional descriptions for the operation. + :vartype properties: dict[str, any] + """ + + _validation = { + 'name': {'readonly': True}, + 'display': {'readonly': True}, + 'origin': {'readonly': True}, + 'properties': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'OperationDisplay'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{object}'}, + } + + def __init__( + self, + *, + is_data_action: Optional[bool] = None, + **kwargs + ): + super(Operation, self).__init__(**kwargs) + self.name = None + self.display = None + self.is_data_action = is_data_action + self.origin = None + self.properties = None + + +class OperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: Operation resource provider name. + :vartype provider: str + :ivar resource: Resource on which the operation is performed. + :vartype resource: str + :ivar operation: Localized friendly name for the operation. + :vartype operation: str + :ivar description: Operation description. + :vartype description: str + """ + + _validation = { + 'provider': {'readonly': True}, + 'resource': {'readonly': True}, + 'operation': {'readonly': True}, + 'description': {'readonly': True}, + } + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationDisplay, self).__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(msrest.serialization.Model): + """A list of resource provider operations. + + :param value: Collection of available operation details. + :type value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Operation] + :param next_link: URL client should use to fetch the next page (per server side paging). + It's null for now, added for future use. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Operation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["Operation"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + super(OperationListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RestartParameter(msrest.serialization.Model): + """Represents server restart parameters. + + :param restart_with_failover: Indicates whether to restart the server with failover. + :type restart_with_failover: bool + :param failover_mode: Failover mode. Possible values include: "PlannedFailover", + "ForcedFailover", "PlannedSwitchover", "ForcedSwitchover". + :type failover_mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.FailoverMode + """ + + _attribute_map = { + 'restart_with_failover': {'key': 'restartWithFailover', 'type': 'bool'}, + 'failover_mode': {'key': 'failoverMode', 'type': 'str'}, + } + + def __init__( + self, + *, + restart_with_failover: Optional[bool] = None, + failover_mode: Optional[Union[str, "FailoverMode"]] = None, + **kwargs + ): + super(RestartParameter, self).__init__(**kwargs) + self.restart_with_failover = restart_with_failover + self.failover_mode = failover_mode + + +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + **kwargs + ): + super(TrackedResource, self).__init__(**kwargs) + self.tags = tags + self.location = location + + +class Server(TrackedResource): + """Represents a server. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :param tags: A set of tags. Resource tags. + :type tags: dict[str, str] + :param location: Required. The geo-location where the resource lives. + :type location: str + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Sku + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :param administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). + :type administrator_login: str + :param administrator_login_password: The administrator login password (required for server + creation). + :type administrator_login_password: str + :param version: PostgreSQL Server version. Possible values include: "13", "12", "11". + :type version: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerVersion + :ivar minor_version: The minor version of the server. + :vartype minor_version: str + :ivar state: A state of a server that is visible to user. Possible values include: "Ready", + "Dropping", "Disabled", "Starting", "Stopping", "Stopped", "Updating". + :vartype state: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerState + :ivar fully_qualified_domain_name: The fully qualified domain name of a server. + :vartype fully_qualified_domain_name: str + :param storage: Storage properties of a server. + :type storage: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Storage + :param backup: Backup properties of a server. + :type backup: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Backup + :param network: Network properties of a server. + :type network: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Network + :param high_availability: High availability properties of a server. + :type high_availability: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.HighAvailability + :param maintenance_window: Maintenance window properties of a server. + :type maintenance_window: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.MaintenanceWindow + :param source_server_resource_id: The source server resource ID to restore from. It's required + when 'createMode' is 'PointInTimeRestore'. + :type source_server_resource_id: str + :param point_in_time_utc: Restore point creation time (ISO8601 format), specifying the time to + restore from. It's required when 'createMode' is 'PointInTimeRestore'. + :type point_in_time_utc: ~datetime.datetime + :param availability_zone: availability zone information of the server. + :type availability_zone: str + :param create_mode: The mode to create a new PostgreSQL server. Possible values include: + "Default", "Create", "Update", "PointInTimeRestore". + :type create_mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreateMode + :param tags_properties_tags: Application-specific metadata in the form of key-value pairs. + :type tags_properties_tags: dict[str, str] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'location': {'required': True}, + 'system_data': {'readonly': True}, + 'minor_version': {'readonly': True}, + 'state': {'readonly': True}, + 'fully_qualified_domain_name': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'location': {'key': 'location', 'type': 'str'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'administrator_login': {'key': 'properties.administratorLogin', 'type': 'str'}, + 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'minor_version': {'key': 'properties.minorVersion', 'type': 'str'}, + 'state': {'key': 'properties.state', 'type': 'str'}, + 'fully_qualified_domain_name': {'key': 'properties.fullyQualifiedDomainName', 'type': 'str'}, + 'storage': {'key': 'properties.storage', 'type': 'Storage'}, + 'backup': {'key': 'properties.backup', 'type': 'Backup'}, + 'network': {'key': 'properties.network', 'type': 'Network'}, + 'high_availability': {'key': 'properties.highAvailability', 'type': 'HighAvailability'}, + 'maintenance_window': {'key': 'properties.maintenanceWindow', 'type': 'MaintenanceWindow'}, + 'source_server_resource_id': {'key': 'properties.sourceServerResourceId', 'type': 'str'}, + 'point_in_time_utc': {'key': 'properties.pointInTimeUTC', 'type': 'iso-8601'}, + 'availability_zone': {'key': 'properties.availabilityZone', 'type': 'str'}, + 'create_mode': {'key': 'properties.createMode', 'type': 'str'}, + 'tags_properties_tags': {'key': 'properties.tags', 'type': '{str}'}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + sku: Optional["Sku"] = None, + administrator_login: Optional[str] = None, + administrator_login_password: Optional[str] = None, + version: Optional[Union[str, "ServerVersion"]] = None, + storage: Optional["Storage"] = None, + backup: Optional["Backup"] = None, + network: Optional["Network"] = None, + high_availability: Optional["HighAvailability"] = None, + maintenance_window: Optional["MaintenanceWindow"] = None, + source_server_resource_id: Optional[str] = None, + point_in_time_utc: Optional[datetime.datetime] = None, + availability_zone: Optional[str] = None, + create_mode: Optional[Union[str, "CreateMode"]] = None, + tags_properties_tags: Optional[Dict[str, str]] = None, + **kwargs + ): + super(Server, self).__init__(tags=tags, location=location, **kwargs) + self.sku = sku + self.system_data = None + self.administrator_login = administrator_login + self.administrator_login_password = administrator_login_password + self.version = version + self.minor_version = None + self.state = None + self.fully_qualified_domain_name = None + self.storage = storage + self.backup = backup + self.network = network + self.high_availability = high_availability + self.maintenance_window = maintenance_window + self.source_server_resource_id = source_server_resource_id + self.point_in_time_utc = point_in_time_utc + self.availability_zone = availability_zone + self.create_mode = create_mode + self.tags_properties_tags = tags_properties_tags + + +class ServerForUpdate(msrest.serialization.Model): + """Represents a server to be updated. + + :param location: The location the resource resides in. + :type location: str + :param sku: The SKU (pricing tier) of the server. + :type sku: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Sku + :param tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :type tags: dict[str, str] + :param administrator_login_password: The password of the administrator login. + :type administrator_login_password: str + :param storage: Storage properties of a server. + :type storage: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Storage + :param backup: Backup properties of a server. + :type backup: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Backup + :param high_availability: High availability properties of a server. + :type high_availability: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.HighAvailability + :param maintenance_window: Maintenance window properties of a server. + :type maintenance_window: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.MaintenanceWindow + :param create_mode: The mode to update a new PostgreSQL server. Possible values include: + "Default", "Update". + :type create_mode: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreateModeForUpdate + """ + + _attribute_map = { + 'location': {'key': 'location', 'type': 'str'}, + 'sku': {'key': 'sku', 'type': 'Sku'}, + 'tags': {'key': 'tags', 'type': '{str}'}, + 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, + 'storage': {'key': 'properties.storage', 'type': 'Storage'}, + 'backup': {'key': 'properties.backup', 'type': 'Backup'}, + 'high_availability': {'key': 'properties.highAvailability', 'type': 'HighAvailability'}, + 'maintenance_window': {'key': 'properties.maintenanceWindow', 'type': 'MaintenanceWindow'}, + 'create_mode': {'key': 'properties.createMode', 'type': 'str'}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + sku: Optional["Sku"] = None, + tags: Optional[Dict[str, str]] = None, + administrator_login_password: Optional[str] = None, + storage: Optional["Storage"] = None, + backup: Optional["Backup"] = None, + high_availability: Optional["HighAvailability"] = None, + maintenance_window: Optional["MaintenanceWindow"] = None, + create_mode: Optional[Union[str, "CreateModeForUpdate"]] = None, + **kwargs + ): + super(ServerForUpdate, self).__init__(**kwargs) + self.location = location + self.sku = sku + self.tags = tags + self.administrator_login_password = administrator_login_password + self.storage = storage + self.backup = backup + self.high_availability = high_availability + self.maintenance_window = maintenance_window + self.create_mode = create_mode + + +class ServerListResult(msrest.serialization.Model): + """A list of servers. + + :param value: The list of flexible servers. + :type value: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Server] + :param next_link: The link used to get the next page of operations. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Server]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["Server"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + super(ServerListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ServerVersionCapability(msrest.serialization.Model): + """Server version capabilities. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: server version. + :vartype name: str + :ivar supported_vcores: + :vartype supported_vcores: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.VcoreCapability] + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_vcores': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_vcores': {'key': 'supportedVcores', 'type': '[VcoreCapability]'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ServerVersionCapability, self).__init__(**kwargs) + self.name = None + self.supported_vcores = None + self.status = None + + +class Sku(msrest.serialization.Model): + """Sku information related properties of a server. + + All required parameters must be populated in order to send to Azure. + + :param name: Required. The name of the sku, typically, tier + family + cores, e.g. + Standard_D4s_v3. + :type name: str + :param tier: Required. The tier of the particular SKU, e.g. Burstable. Possible values include: + "Burstable", "GeneralPurpose", "MemoryOptimized". + :type tier: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SkuTier + """ + + _validation = { + 'name': {'required': True}, + 'tier': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'tier': {'key': 'tier', 'type': 'str'}, + } + + def __init__( + self, + *, + name: str, + tier: Union[str, "SkuTier"], + **kwargs + ): + super(Sku, self).__init__(**kwargs) + self.name = name + self.tier = tier + + +class Storage(msrest.serialization.Model): + """Storage properties of a server. + + :param storage_size_gb: Max storage allowed for a server. + :type storage_size_gb: int + """ + + _attribute_map = { + 'storage_size_gb': {'key': 'storageSizeGB', 'type': 'int'}, + } + + def __init__( + self, + *, + storage_size_gb: Optional[int] = None, + **kwargs + ): + super(Storage, self).__init__(**kwargs) + self.storage_size_gb = storage_size_gb + + +class StorageEditionCapability(msrest.serialization.Model): + """storage edition capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: storage edition name. + :vartype name: str + :ivar supported_storage_mb: + :vartype supported_storage_mb: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.StorageMBCapability] + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_storage_mb': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_storage_mb': {'key': 'supportedStorageMB', 'type': '[StorageMBCapability]'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(StorageEditionCapability, self).__init__(**kwargs) + self.name = None + self.supported_storage_mb = None + self.status = None + + +class StorageMBCapability(msrest.serialization.Model): + """storage size in MB capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: storage MB name. + :vartype name: str + :ivar supported_iops: supported IOPS. + :vartype supported_iops: long + :ivar storage_size_mb: storage size in MB. + :vartype storage_size_mb: long + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'supported_iops': {'readonly': True}, + 'storage_size_mb': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'supported_iops': {'key': 'supportedIops', 'type': 'long'}, + 'storage_size_mb': {'key': 'storageSizeMB', 'type': 'long'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(StorageMBCapability, self).__init__(**kwargs) + self.name = None + self.supported_iops = None + self.storage_size_mb = None + self.status = None + + +class SystemData(msrest.serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :param created_by: The identity that created the resource. + :type created_by: str + :param created_by_type: The type of identity that created the resource. Possible values + include: "User", "Application", "ManagedIdentity", "Key". + :type created_by_type: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreatedByType + :param created_at: The timestamp of resource creation (UTC). + :type created_at: ~datetime.datetime + :param last_modified_by: The identity that last modified the resource. + :type last_modified_by: str + :param last_modified_by_type: The type of identity that last modified the resource. Possible + values include: "User", "Application", "ManagedIdentity", "Key". + :type last_modified_by_type: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreatedByType + :param last_modified_at: The timestamp of resource last modification (UTC). + :type last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + 'created_by': {'key': 'createdBy', 'type': 'str'}, + 'created_by_type': {'key': 'createdByType', 'type': 'str'}, + 'created_at': {'key': 'createdAt', 'type': 'iso-8601'}, + 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'str'}, + 'last_modified_by_type': {'key': 'lastModifiedByType', 'type': 'str'}, + 'last_modified_at': {'key': 'lastModifiedAt', 'type': 'iso-8601'}, + } + + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs + ): + super(SystemData, self).__init__(**kwargs) + self.created_by = created_by + self.created_by_type = created_by_type + self.created_at = created_at + self.last_modified_by = last_modified_by + self.last_modified_by_type = last_modified_by_type + self.last_modified_at = last_modified_at + + +class VcoreCapability(msrest.serialization.Model): + """Vcores capability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: vCore name. + :vartype name: str + :ivar v_cores: supported vCores. + :vartype v_cores: long + :ivar supported_iops: supported IOPS. + :vartype supported_iops: long + :ivar supported_memory_per_vcore_mb: supported memory per vCore in MB. + :vartype supported_memory_per_vcore_mb: long + :ivar status: The status. + :vartype status: str + """ + + _validation = { + 'name': {'readonly': True}, + 'v_cores': {'readonly': True}, + 'supported_iops': {'readonly': True}, + 'supported_memory_per_vcore_mb': {'readonly': True}, + 'status': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'v_cores': {'key': 'vCores', 'type': 'long'}, + 'supported_iops': {'key': 'supportedIops', 'type': 'long'}, + 'supported_memory_per_vcore_mb': {'key': 'supportedMemoryPerVcoreMB', 'type': 'long'}, + 'status': {'key': 'status', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(VcoreCapability, self).__init__(**kwargs) + self.name = None + self.v_cores = None + self.supported_iops = None + self.supported_memory_per_vcore_mb = None + self.status = None + + +class VirtualNetworkSubnetUsageParameter(msrest.serialization.Model): + """Virtual network subnet usage parameter. + + :param virtual_network_arm_resource_id: Virtual network resource id. + :type virtual_network_arm_resource_id: str + """ + + _attribute_map = { + 'virtual_network_arm_resource_id': {'key': 'virtualNetworkArmResourceId', 'type': 'str'}, + } + + def __init__( + self, + *, + virtual_network_arm_resource_id: Optional[str] = None, + **kwargs + ): + super(VirtualNetworkSubnetUsageParameter, self).__init__(**kwargs) + self.virtual_network_arm_resource_id = virtual_network_arm_resource_id + + +class VirtualNetworkSubnetUsageResult(msrest.serialization.Model): + """Virtual network subnet usage data. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar delegated_subnets_usage: + :vartype delegated_subnets_usage: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.DelegatedSubnetUsage] + """ + + _validation = { + 'delegated_subnets_usage': {'readonly': True}, + } + + _attribute_map = { + 'delegated_subnets_usage': {'key': 'delegatedSubnetsUsage', 'type': '[DelegatedSubnetUsage]'}, + } + + def __init__( + self, + **kwargs + ): + super(VirtualNetworkSubnetUsageResult, self).__init__(**kwargs) + self.delegated_subnets_usage = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/_postgre_sql_management_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/_postgre_sql_management_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..16a0ab4ace10d3533119ec6cc2237522cd552595 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/models/_postgre_sql_management_client_enums.py @@ -0,0 +1,138 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum, EnumMeta +from six import with_metaclass + +class _CaseInsensitiveEnumMeta(EnumMeta): + def __getitem__(self, name): + return super().__getitem__(name.upper()) + + def __getattr__(cls, name): + """Return the enum member matching `name` + We use __getattr__ instead of descriptors or inserting into the enum + class' __dict__ in order to support `name` and `value` being both + properties for enum members (which live in the class' __dict__) and + enum members themselves. + """ + try: + return cls._member_map_[name.upper()] + except KeyError: + raise AttributeError(name) + + +class ConfigurationDataType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Data type of the configuration. + """ + + BOOLEAN = "Boolean" + NUMERIC = "Numeric" + INTEGER = "Integer" + ENUMERATION = "Enumeration" + +class CreatedByType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The type of identity that created the resource. + """ + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + +class CreateMode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The mode to create a new PostgreSQL server. + """ + + DEFAULT = "Default" + CREATE = "Create" + UPDATE = "Update" + POINT_IN_TIME_RESTORE = "PointInTimeRestore" + +class CreateModeForUpdate(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The mode to update a new PostgreSQL server. + """ + + DEFAULT = "Default" + UPDATE = "Update" + +class FailoverMode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Failover mode. + """ + + PLANNED_FAILOVER = "PlannedFailover" + FORCED_FAILOVER = "ForcedFailover" + PLANNED_SWITCHOVER = "PlannedSwitchover" + FORCED_SWITCHOVER = "ForcedSwitchover" + +class GeoRedundantBackupEnum(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """A value indicating whether Geo-Redundant backup is enabled on the server. + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class HighAvailabilityMode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The HA mode for the server. + """ + + DISABLED = "Disabled" + ZONE_REDUNDANT = "ZoneRedundant" + +class OperationOrigin(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The intended executor of the operation. + """ + + NOT_SPECIFIED = "NotSpecified" + USER = "user" + SYSTEM = "system" + +class ServerHAState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """A state of a HA server that is visible to user. + """ + + NOT_ENABLED = "NotEnabled" + CREATING_STANDBY = "CreatingStandby" + REPLICATING_DATA = "ReplicatingData" + FAILING_OVER = "FailingOver" + HEALTHY = "Healthy" + REMOVING_STANDBY = "RemovingStandby" + +class ServerPublicNetworkAccessState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """public network access is enabled or not + """ + + ENABLED = "Enabled" + DISABLED = "Disabled" + +class ServerState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """A state of a server that is visible to user. + """ + + READY = "Ready" + DROPPING = "Dropping" + DISABLED = "Disabled" + STARTING = "Starting" + STOPPING = "Stopping" + STOPPED = "Stopped" + UPDATING = "Updating" + +class ServerVersion(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The version of a server. + """ + + THIRTEEN = "13" + TWELVE = "12" + ELEVEN = "11" + +class SkuTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The tier of the particular SKU, e.g. Burstable. + """ + + BURSTABLE = "Burstable" + GENERAL_PURPOSE = "GeneralPurpose" + MEMORY_OPTIMIZED = "MemoryOptimized" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d0788161037b77537d23b160907dc3839b15fffe --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._servers_operations import ServersOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._configurations_operations import ConfigurationsOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._location_based_capabilities_operations import LocationBasedCapabilitiesOperations +from ._virtual_network_subnet_usage_operations import VirtualNetworkSubnetUsageOperations +from ._operations import Operations +from ._databases_operations import DatabasesOperations +from ._get_private_dns_zone_suffix_operations import GetPrivateDnsZoneSuffixOperations + +__all__ = [ + 'ServersOperations', + 'FirewallRulesOperations', + 'ConfigurationsOperations', + 'CheckNameAvailabilityOperations', + 'LocationBasedCapabilitiesOperations', + 'VirtualNetworkSubnetUsageOperations', + 'Operations', + 'DatabasesOperations', + 'GetPrivateDnsZoneSuffixOperations', +] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_check_name_availability_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_check_name_availability_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..72db42121da1e357d0b7f1c9f89316142b5766f2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_check_name_availability_operations.py @@ -0,0 +1,105 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class CheckNameAvailabilityOperations(object): + """CheckNameAvailabilityOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def execute( + self, + name_availability_request, # type: "_models.NameAvailabilityRequest" + **kwargs # type: Any + ): + # type: (...) -> "_models.NameAvailability" + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. + :type name_availability_request: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.NameAvailabilityRequest + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.NameAvailability + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.execute.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('NameAvailability', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_configurations_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_configurations_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..ced514dbf688fa7fab44b4512bddfde4e11dc233 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_configurations_operations.py @@ -0,0 +1,456 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ConfigurationsOperations(object): + """ConfigurationsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ConfigurationListResult"] + """List all the configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConfigurationListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ConfigurationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.Configuration" + """Gets information about a configuration of server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Configuration, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + def _update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + configuration_name, # type: str + parameters, # type: "_models.Configuration" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Configuration"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Configuration') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + def begin_update( + self, + resource_group_name, # type: str + server_name, # type: str + configuration_name, # type: str + parameters, # type: "_models.Configuration" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Configuration"] + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Configuration or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + def _put_initial( + self, + resource_group_name, # type: str + server_name, # type: str + configuration_name, # type: str + parameters, # type: "_models.Configuration" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Configuration"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Configuration"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._put_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Configuration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _put_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore + + def begin_put( + self, + resource_group_name, # type: str + server_name, # type: str + configuration_name, # type: str + parameters, # type: "_models.Configuration" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Configuration"] + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param configuration_name: The name of the server configuration. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Configuration or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Configuration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._put_initial( + resource_group_name=resource_group_name, + server_name=server_name, + configuration_name=configuration_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Configuration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_put.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_databases_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_databases_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..fc3e8294a72973a146bd0e676fbf68be7e94482f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_databases_operations.py @@ -0,0 +1,441 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class DatabasesOperations(object): + """DatabasesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_initial( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + parameters, # type: "_models.Database" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Database"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Database"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Database') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Database', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + def begin_create( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + parameters, # type: "_models.Database" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Database"] + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Database + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Database or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + database_name=database_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + database_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.Database" + """Gets information about a database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param database_name: The name of the database. + :type database_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Database, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Database + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Database"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'databaseName': self._serialize.url("database_name", database_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Database', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.DatabaseListResult"] + """List all the databases in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DatabaseListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.DatabaseListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.DatabaseListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('DatabaseListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_firewall_rules_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_firewall_rules_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..843d8087c45fd1e9ae194ccf8a129be00f977f74 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_firewall_rules_operations.py @@ -0,0 +1,441 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class FirewallRulesOperations(object): + """FirewallRulesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_or_update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + parameters, # type: "_models.FirewallRule" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.FirewallRule"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.FirewallRule"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'FirewallRule') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + parameters, # type: "_models.FirewallRule" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.FirewallRule"] + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.FirewallRule + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either FirewallRule or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes a PostgreSQL server firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + firewall_rule_name=firewall_rule_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + firewall_rule_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.FirewallRule" + """List all the firewall rules in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. + :type firewall_rule_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FirewallRule, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.FirewallRule + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRule"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + 'firewallRuleName': self._serialize.url("firewall_rule_name", firewall_rule_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FirewallRule', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}'} # type: ignore + + def list_by_server( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.FirewallRuleListResult"] + """List all the firewall rules in a given PostgreSQL server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FirewallRuleListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.FirewallRuleListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FirewallRuleListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_server.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('FirewallRuleListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_server.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb6e67f4d4b48c399dfe7f31a35ae4b8afdb864 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py @@ -0,0 +1,92 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class GetPrivateDnsZoneSuffixOperations(object): + """GetPrivateDnsZoneSuffixOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def execute( + self, + **kwargs # type: Any + ): + # type: (...) -> str + """Get private DNS zone suffix in the cloud. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: str, or the result of cls(response) + :rtype: str + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType[str] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.execute.metadata['url'] # type: ignore + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('str', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + execute.metadata = {'url': '/providers/Microsoft.DBforPostgreSQL/getPrivateDnsZoneSuffix'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_location_based_capabilities_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_location_based_capabilities_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb8a50d7e651cf7e47b810aec409c80d684e97d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_location_based_capabilities_operations.py @@ -0,0 +1,117 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class LocationBasedCapabilitiesOperations(object): + """LocationBasedCapabilitiesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def execute( + self, + location_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.CapabilitiesListResult"] + """Get capabilities at specified location in a given subscription. + + :param location_name: The name of the location. + :type location_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either CapabilitiesListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.CapabilitiesListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.CapabilitiesListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.execute.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('CapabilitiesListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/capabilities'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..9f7c8945bbb335fe436ab11a119e23e29ea730fd --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_operations.py @@ -0,0 +1,92 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class Operations(object): + """Operations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> "_models.OperationListResult" + """Lists all of the available REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationListResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.OperationListResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.list.metadata['url'] # type: ignore + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationListResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + list.metadata = {'url': '/providers/Microsoft.DBforPostgreSQL/operations'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_servers_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_servers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..9ba2a521dd597f13a8c796589610274307c76960 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_servers_operations.py @@ -0,0 +1,958 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ServersOperations(object): + """ServersOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_initial( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.Server" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Server"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'Server') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + def begin_create( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.Server" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Server"] + """Creates a new server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Server + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + def _update_initial( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.ServerForUpdate" + **kwargs # type: Any + ): + # type: (...) -> Optional["_models.Server"] + cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Server"]] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'ServerForUpdate') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + def begin_update( + self, + resource_group_name, # type: str + server_name, # type: str + parameters, # type: "_models.ServerForUpdate" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Server"] + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The required parameters for updating a server. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerForUpdate + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Deletes a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.Server" + """Gets information about a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Server, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Server + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Server"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Server', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}'} # type: ignore + + def list_by_resource_group( + self, + resource_group_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerListResult"] + """List all the servers in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list_by_resource_group.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers'} # type: ignore + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ServerListResult"] + """List all the servers in a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ServerListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ServerListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ServerListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/flexibleServers'} # type: ignore + + def _restart_initial( + self, + resource_group_name, # type: str + server_name, # type: str + parameters=None, # type: Optional["_models.RestartParameter"] + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._restart_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + if parameters is not None: + body_content = self._serialize.body(parameters, 'RestartParameter') + else: + body_content = None + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/restart'} # type: ignore + + def begin_restart( + self, + resource_group_name, # type: str + server_name, # type: str + parameters=None, # type: Optional["_models.RestartParameter"] + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :param parameters: The parameters for restarting a server. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.RestartParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._restart_initial( + resource_group_name=resource_group_name, + server_name=server_name, + parameters=parameters, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/restart'} # type: ignore + + def _start_initial( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self._start_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/start'} # type: ignore + + def begin_start( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Starts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._start_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/start'} # type: ignore + + def _stop_initial( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + accept = "application/json" + + # Construct URL + url = self._stop_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.post(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _stop_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/stop'} # type: ignore + + def begin_stop( + self, + resource_group_name, # type: str + server_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Stops a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param server_name: The name of the server. + :type server_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._stop_initial( + resource_group_name=resource_group_name, + server_name=server_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + 'serverName': self._serialize.url("server_name", server_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/stop'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_virtual_network_subnet_usage_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_virtual_network_subnet_usage_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..3979cd029d6aca14372981b41cf9b3ec0ba96594 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_virtual_network_subnet_usage_operations.py @@ -0,0 +1,108 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class VirtualNetworkSubnetUsageOperations(object): + """VirtualNetworkSubnetUsageOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.rdbms.postgresql_flexibleservers.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def execute( + self, + location_name, # type: str + parameters, # type: "_models.VirtualNetworkSubnetUsageParameter" + **kwargs # type: Any + ): + # type: (...) -> "_models.VirtualNetworkSubnetUsageResult" + """Get virtual network subnet usage for a given vNet resource id. + + :param location_name: The name of the location. + :type location_name: str + :param parameters: The required parameters for creating or updating a server. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.VirtualNetworkSubnetUsageParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkSubnetUsageResult, or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.VirtualNetworkSubnetUsageResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkSubnetUsageResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.execute.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'locationName': self._serialize.url("location_name", location_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'VirtualNetworkSubnetUsageParameter') + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize('VirtualNetworkSubnetUsageResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + execute.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/checkVirtualNetworkSubnetUsage'} # type: ignore diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..50070c4b6b0dc0c273e0488380dc072428801ff1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._changes_client import ChangesClient +__all__ = ['ChangesClient'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/aio/_changes_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/aio/_changes_client.py new file mode 100644 index 0000000000000000000000000000000000000000..662cda295ccec7d29dfd77f185ba178db41b2a65 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/aio/_changes_client.py @@ -0,0 +1,115 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.mgmt.core import AsyncARMPipelineClient +from azure.profiles import KnownProfiles, ProfileDefinition +from azure.profiles.multiapiclient import MultiApiClientMixin + +from .._serialization import Deserializer, Serializer +from ._configuration import ChangesClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class _SDKClient(object): + def __init__(self, *args, **kwargs): + """This is a fake class to support current implemetation of MultiApiClientMixin." + Will be removed in final version of multiapi azure-core based client + """ + pass + +class ChangesClient(MultiApiClientMixin, _SDKClient): + """The Resource Changes Client. + + This ready contains multiple API versions, to help you deal with all of the Azure clouds + (Azure Stack, Azure Government, Azure China, etc.). + By default, it uses the latest API version available on public Azure. + For production, you should stick to a particular api-version and/or profile. + The profile sets a mapping between an operation group and its API version. + The api-version parameter sets the default API version if the operation + group is not described in the profile. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + :param api_version: API version to use if no profile is provided, or if missing in profile. + :type api_version: str + :param base_url: Service URL + :type base_url: str + :param profile: A profile definition, from KnownProfiles to dict. + :type profile: azure.profiles.KnownProfiles + """ + + DEFAULT_API_VERSION = '2022-05-01' + _PROFILE_TAG = "azure.mgmt.resource.changes.ChangesClient" + LATEST_PROFILE = ProfileDefinition({ + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + }}, + _PROFILE_TAG + " latest" + ) + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + api_version: Optional[str] = None, + base_url: str = "https://management.azure.com", + profile: KnownProfiles = KnownProfiles.default, + **kwargs: Any + ) -> None: + self._config = ChangesClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + super(ChangesClient, self).__init__( + api_version=api_version, + profile=profile + ) + + @classmethod + def _models_dict(cls, api_version): + return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} + + @classmethod + def models(cls, api_version=DEFAULT_API_VERSION): + """Module depends on the API version: + + * 2022-05-01: :mod:`v2022_05_01.models` + """ + if api_version == '2022-05-01': + from ..v2022_05_01 import models + return models + raise ValueError("API version {} is not available".format(api_version)) + + @property + def changes(self): + """Instance depends on the API version: + + * 2022-05-01: :class:`ChangesOperations` + """ + api_version = self._get_api_version('changes') + if api_version == '2022-05-01': + from ..v2022_05_01.aio.operations import ChangesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'changes'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + async def close(self): + await self._client.close() + async def __aenter__(self): + await self._client.__aenter__() + return self + async def __aexit__(self, *exc_details): + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f7b12c959304aa1c666a8451a6d8b48779061e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class ChangesClientConfiguration(Configuration): + """Configuration for ChangesClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(ChangesClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'azure-mgmt-resource/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63e926ebaebb03e50dc76c563480332ebfb483dd --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._changes_client import ChangesClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ChangesClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_changes_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_changes_client.py new file mode 100644 index 0000000000000000000000000000000000000000..9406fce1d9ee1fb613ed694a95cff374dfec8b25 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_changes_client.py @@ -0,0 +1,88 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import ChangesClientConfiguration +from .operations import ChangesOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class ChangesClient: # pylint: disable=client-accepts-api-version-keyword + """The Resource Changes Client. + + :ivar changes: ChangesOperations operations + :vartype changes: azure.mgmt.resource.changes.v2022_05_01.operations.ChangesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ChangesClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.changes = ChangesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "ChangesClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..f090c0685f1112db610011353ed0aaca110ba912 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_configuration.py @@ -0,0 +1,73 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class ChangesClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ChangesClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ChangesClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2022-05-01"] = kwargs.pop("api_version", "2022-05-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0df84f5319f2e522d0fec4553e2e8b04bf904a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_vendor.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import List, cast + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..38ced0793f4166879d6ef8932a3e97f0cf1f3239 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "23.0.1" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fc466c6c0f3d73407f1808a714e40f4d082ee15b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._changes_client import ChangesClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ChangesClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/_changes_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/_changes_client.py new file mode 100644 index 0000000000000000000000000000000000000000..1b43918bf281f262ccdaa48888423dfb47ee9e72 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/_changes_client.py @@ -0,0 +1,88 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import ChangesClientConfiguration +from .operations import ChangesOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class ChangesClient: # pylint: disable=client-accepts-api-version-keyword + """The Resource Changes Client. + + :ivar changes: ChangesOperations operations + :vartype changes: azure.mgmt.resource.changes.v2022_05_01.aio.operations.ChangesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ChangesClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.changes = ChangesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "ChangesClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..f48681ffd04b528ec74c1f552e5841b515f891fd --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/_configuration.py @@ -0,0 +1,73 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class ChangesClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ChangesClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-05-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ChangesClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2022-05-01"] = kwargs.pop("api_version", "2022-05-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..be934d4074cf21b02bfb4ba098a15d4521157763 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import ChangesOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ChangesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..1c953969f1abbc0df79c75bb137ec0f5cc0cdb92 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/operations/_operations.py @@ -0,0 +1,250 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_changes_get_request, build_changes_list_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ChangesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.changes.v2022_05_01.aio.ChangesClient`'s + :attr:`changes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + top: int = 100, + skip_token: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.ChangeResourceResult"]: + """Obtains a list of change resources from the past 14 days for the target resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The name of the resource provider namespace. Required. + :type resource_provider_namespace: str + :param resource_type: The name of the resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param top: (Optional) Set the maximum number of results per response. Default value is 100. + :type top: int + :param skip_token: (Optional) The page-continuation token. Default value is None. + :type skip_token: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ChangeResourceResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.changes.v2022_05_01.models.ChangeResourceResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) + cls: ClsType[_models.ChangeResourceListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_changes_list_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + top=top, + skip_token=skip_token, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ChangeResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Resources/changes" + } + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + change_resource_id: str, + **kwargs: Any + ) -> _models.ChangeResourceResult: + """Obtains the specified change resource for the target resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The name of the resource provider namespace. Required. + :type resource_provider_namespace: str + :param resource_type: The name of the resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param change_resource_id: The ID of the change resource. Required. + :type change_resource_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ChangeResourceResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.changes.v2022_05_01.models.ChangeResourceResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) + cls: ClsType[_models.ChangeResourceResult] = kwargs.pop("cls", None) + + request = build_changes_get_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + change_resource_id=change_resource_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ChangeResourceResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Resources/changes/{changeResourceId}" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed07c9c19e1cc1c4f529e621dba01def9d7a69b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/__init__.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import ChangeAttributes +from ._models_py3 import ChangeBase +from ._models_py3 import ChangeProperties +from ._models_py3 import ChangeResourceListResult +from ._models_py3 import ChangeResourceResult +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import Resource + +from ._changes_client_enums import ChangeCategory +from ._changes_client_enums import ChangeType +from ._changes_client_enums import PropertyChangeType +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ChangeAttributes", + "ChangeBase", + "ChangeProperties", + "ChangeResourceListResult", + "ChangeResourceResult", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "Resource", + "ChangeCategory", + "ChangeType", + "PropertyChangeType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/_changes_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/_changes_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..996871a4dc8d06de36a591a43bae7cf1d456f1c2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/_changes_client_enums.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ChangeCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The entity that made the change.""" + + USER = "User" + """User initiated change""" + SYSTEM = "System" + """System initiated change""" + + +class ChangeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of change that was captured in the resource.""" + + UPDATE = "Update" + """An existing resource underwent a change""" + DELETE = "Delete" + """An existing resource was deleted""" + CREATE = "Create" + """A newly created resource""" + + +class PropertyChangeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of change that occurred.""" + + UPDATE = "Update" + """An existing property underwent a change""" + INSERT = "Insert" + """A property was newly created""" + REMOVE = "Remove" + """An existing property was deleted""" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..bd729a07cc1ad3905d070b0b396f2728d24111b8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/_models_py3.py @@ -0,0 +1,353 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Dict, List, Optional, TYPE_CHECKING + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class ChangeAttributes(_serialization.Model): + """Details about the change resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar correlation_id: The ARM correlation ID of the change resource. + :vartype correlation_id: str + :ivar timestamp: The time the change(s) on the target resource ocurred. + :vartype timestamp: str + :ivar changes_count: The number of changes this resource captures. + :vartype changes_count: int + :ivar previous_resource_snapshot_id: The GUID of the previous snapshot. + :vartype previous_resource_snapshot_id: str + :ivar new_resource_snapshot_id: The GUID of the new snapshot. + :vartype new_resource_snapshot_id: str + """ + + _validation = { + "correlation_id": {"readonly": True}, + "timestamp": {"readonly": True}, + "changes_count": {"readonly": True}, + "previous_resource_snapshot_id": {"readonly": True}, + "new_resource_snapshot_id": {"readonly": True}, + } + + _attribute_map = { + "correlation_id": {"key": "correlationId", "type": "str"}, + "timestamp": {"key": "timestamp", "type": "str"}, + "changes_count": {"key": "changesCount", "type": "int"}, + "previous_resource_snapshot_id": {"key": "previousResourceSnapshotId", "type": "str"}, + "new_resource_snapshot_id": {"key": "newResourceSnapshotId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.correlation_id = None + self.timestamp = None + self.changes_count = None + self.previous_resource_snapshot_id = None + self.new_resource_snapshot_id = None + + +class ChangeBase(_serialization.Model): + """An individual change on the target resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar property_change_type: The type of change that occurred. Known values are: "Update", + "Insert", and "Remove". + :vartype property_change_type: str or + ~azure.mgmt.resource.changes.v2022_05_01.models.PropertyChangeType + :ivar change_category: The entity that made the change. Known values are: "User" and "System". + :vartype change_category: str or ~azure.mgmt.resource.changes.v2022_05_01.models.ChangeCategory + :ivar previous_value: The target resource property value before the change. + :vartype previous_value: str + :ivar new_value: The target resource property value after the change. + :vartype new_value: str + """ + + _validation = { + "property_change_type": {"readonly": True}, + "change_category": {"readonly": True}, + "previous_value": {"readonly": True}, + "new_value": {"readonly": True}, + } + + _attribute_map = { + "property_change_type": {"key": "propertyChangeType", "type": "str"}, + "change_category": {"key": "changeCategory", "type": "str"}, + "previous_value": {"key": "previousValue", "type": "str"}, + "new_value": {"key": "newValue", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.property_change_type = None + self.change_category = None + self.previous_value = None + self.new_value = None + + +class ChangeProperties(_serialization.Model): + """The properties of a change. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar target_resource_id: The fully qualified ID of the target resource that was changed. + :vartype target_resource_id: str + :ivar target_resource_type: The namespace and type of the resource. + :vartype target_resource_type: str + :ivar change_type: The type of change that was captured in the resource. Known values are: + "Update", "Delete", and "Create". + :vartype change_type: str or ~azure.mgmt.resource.changes.v2022_05_01.models.ChangeType + :ivar change_attributes: Details about the change resource. + :vartype change_attributes: ~azure.mgmt.resource.changes.v2022_05_01.models.ChangeAttributes + :ivar changes: A dictionary with changed property name as a key and the change details as the + value. + :vartype changes: dict[str, ~azure.mgmt.resource.changes.v2022_05_01.models.ChangeBase] + """ + + _validation = { + "target_resource_id": {"readonly": True}, + "target_resource_type": {"readonly": True}, + "change_type": {"readonly": True}, + } + + _attribute_map = { + "target_resource_id": {"key": "targetResourceId", "type": "str"}, + "target_resource_type": {"key": "targetResourceType", "type": "str"}, + "change_type": {"key": "changeType", "type": "str"}, + "change_attributes": {"key": "changeAttributes", "type": "ChangeAttributes"}, + "changes": {"key": "changes", "type": "{ChangeBase}"}, + } + + def __init__( + self, + *, + change_attributes: Optional["_models.ChangeAttributes"] = None, + changes: Optional[Dict[str, "_models.ChangeBase"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword change_attributes: Details about the change resource. + :paramtype change_attributes: ~azure.mgmt.resource.changes.v2022_05_01.models.ChangeAttributes + :keyword changes: A dictionary with changed property name as a key and the change details as + the value. + :paramtype changes: dict[str, ~azure.mgmt.resource.changes.v2022_05_01.models.ChangeBase] + """ + super().__init__(**kwargs) + self.target_resource_id = None + self.target_resource_type = None + self.change_type = None + self.change_attributes = change_attributes + self.changes = changes + + +class ChangeResourceListResult(_serialization.Model): + """The list of resources. + + :ivar next_link: The link used to get the next page of Change Resources. + :vartype next_link: str + :ivar value: The list of resources. + :vartype value: list[~azure.mgmt.resource.changes.v2022_05_01.models.ChangeResourceResult] + """ + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[ChangeResourceResult]"}, + } + + def __init__( + self, + *, + next_link: Optional[str] = None, + value: Optional[List["_models.ChangeResourceResult"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword next_link: The link used to get the next page of Change Resources. + :paramtype next_link: str + :keyword value: The list of resources. + :paramtype value: list[~azure.mgmt.resource.changes.v2022_05_01.models.ChangeResourceResult] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = value + + +class Resource(_serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class ChangeResourceResult(Resource): + """Change Resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar properties: The properties of a change. + :vartype properties: ~azure.mgmt.resource.changes.v2022_05_01.models.ChangeProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "ChangeProperties"}, + } + + def __init__(self, *, properties: Optional["_models.ChangeProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: The properties of a change. + :paramtype properties: ~azure.mgmt.resource.changes.v2022_05_01.models.ChangeProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.resource.changes.v2022_05_01.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.mgmt.resource.changes.v2022_05_01.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.resource.changes.v2022_05_01.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.resource.changes.v2022_05_01.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..be934d4074cf21b02bfb4ba098a15d4521157763 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import ChangesOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ChangesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..e327fc97ae3fdd9dcb140611b896c6a72fe27439 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/operations/_operations.py @@ -0,0 +1,337 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_changes_list_request( + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + top: int = 100, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Resources/changes", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=100, minimum=1) + if skip_token is not None: + _params["$skipToken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_changes_get_request( + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + change_resource_id: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Resources/changes/{changeResourceId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "changeResourceId": _SERIALIZER.url("change_resource_id", change_resource_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ChangesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.changes.v2022_05_01.ChangesClient`'s + :attr:`changes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + top: int = 100, + skip_token: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.ChangeResourceResult"]: + """Obtains a list of change resources from the past 14 days for the target resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The name of the resource provider namespace. Required. + :type resource_provider_namespace: str + :param resource_type: The name of the resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param top: (Optional) Set the maximum number of results per response. Default value is 100. + :type top: int + :param skip_token: (Optional) The page-continuation token. Default value is None. + :type skip_token: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ChangeResourceResult or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.changes.v2022_05_01.models.ChangeResourceResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) + cls: ClsType[_models.ChangeResourceListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_changes_list_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + top=top, + skip_token=skip_token, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ChangeResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Resources/changes" + } + + @distributed_trace + def get( + self, + resource_group_name: str, + resource_provider_namespace: str, + resource_type: str, + resource_name: str, + change_resource_id: str, + **kwargs: Any + ) -> _models.ChangeResourceResult: + """Obtains the specified change resource for the target resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The name of the resource provider namespace. Required. + :type resource_provider_namespace: str + :param resource_type: The name of the resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param change_resource_id: The ID of the change resource. Required. + :type change_resource_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ChangeResourceResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.changes.v2022_05_01.models.ChangeResourceResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) + cls: ClsType[_models.ChangeResourceResult] = kwargs.pop("cls", None) + + request = build_changes_get_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + resource_type=resource_type, + resource_name=resource_name, + change_resource_id=change_resource_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ChangeResourceResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Resources/changes/{changeResourceId}" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/v2022_05_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5d8dd151ee2e01f47636ab8625fbd123d143b733 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._deployment_scripts_client import DeploymentScriptsClient +__all__ = ['DeploymentScriptsClient'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..0af82ce5a784ea2fb14340473eec4d2abd9781e1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class DeploymentScriptsClientConfiguration(Configuration): + """Configuration for DeploymentScriptsClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: Subscription Id which forms part of the URI for every service call. Required. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(DeploymentScriptsClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'azure-mgmt-resource/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/aio/_deployment_scripts_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/aio/_deployment_scripts_client.py new file mode 100644 index 0000000000000000000000000000000000000000..1147741848f96ca815eb2a95fc108775ddda53fb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/aio/_deployment_scripts_client.py @@ -0,0 +1,123 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.mgmt.core import AsyncARMPipelineClient +from azure.profiles import KnownProfiles, ProfileDefinition +from azure.profiles.multiapiclient import MultiApiClientMixin + +from .._serialization import Deserializer, Serializer +from ._configuration import DeploymentScriptsClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class _SDKClient(object): + def __init__(self, *args, **kwargs): + """This is a fake class to support current implemetation of MultiApiClientMixin." + Will be removed in final version of multiapi azure-core based client + """ + pass + +class DeploymentScriptsClient(MultiApiClientMixin, _SDKClient): + """The APIs listed in this specification can be used to manage Deployment Scripts resource through the Azure Resource Manager. + + This ready contains multiple API versions, to help you deal with all of the Azure clouds + (Azure Stack, Azure Government, Azure China, etc.). + By default, it uses the latest API version available on public Azure. + For production, you should stick to a particular api-version and/or profile. + The profile sets a mapping between an operation group and its API version. + The api-version parameter sets the default API version if the operation + group is not described in the profile. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: Subscription Id which forms part of the URI for every service call. Required. + :type subscription_id: str + :param api_version: API version to use if no profile is provided, or if missing in profile. + :type api_version: str + :param base_url: Service URL + :type base_url: str + :param profile: A profile definition, from KnownProfiles to dict. + :type profile: azure.profiles.KnownProfiles + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + DEFAULT_API_VERSION = '2020-10-01' + _PROFILE_TAG = "azure.mgmt.resource.deploymentscripts.DeploymentScriptsClient" + LATEST_PROFILE = ProfileDefinition({ + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + }}, + _PROFILE_TAG + " latest" + ) + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + api_version: Optional[str] = None, + base_url: str = "https://management.azure.com", + profile: KnownProfiles = KnownProfiles.default, + **kwargs: Any + ) -> None: + self._config = DeploymentScriptsClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + super(DeploymentScriptsClient, self).__init__( + api_version=api_version, + profile=profile + ) + + @classmethod + def _models_dict(cls, api_version): + return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} + + @classmethod + def models(cls, api_version=DEFAULT_API_VERSION): + """Module depends on the API version: + + * 2019-10-01-preview: :mod:`v2019_10_01_preview.models` + * 2020-10-01: :mod:`v2020_10_01.models` + """ + if api_version == '2019-10-01-preview': + from ..v2019_10_01_preview import models + return models + elif api_version == '2020-10-01': + from ..v2020_10_01 import models + return models + raise ValueError("API version {} is not available".format(api_version)) + + @property + def deployment_scripts(self): + """Instance depends on the API version: + + * 2019-10-01-preview: :class:`DeploymentScriptsOperations` + * 2020-10-01: :class:`DeploymentScriptsOperations` + """ + api_version = self._get_api_version('deployment_scripts') + if api_version == '2019-10-01-preview': + from ..v2019_10_01_preview.aio.operations import DeploymentScriptsOperations as OperationClass + elif api_version == '2020-10-01': + from ..v2020_10_01.aio.operations import DeploymentScriptsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'deployment_scripts'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + async def close(self): + await self._client.close() + async def __aenter__(self): + await self._client.__aenter__() + return self + async def __aexit__(self, *exc_details): + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b746eedf3a2f31d113774a3abf6adb83ed943354 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._deployment_scripts_client import DeploymentScriptsClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DeploymentScriptsClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..a3f6597b2eaa7bea2018f92b28aafe2ad01739d0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_configuration.py @@ -0,0 +1,73 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class DeploymentScriptsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for DeploymentScriptsClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: Subscription Id which forms part of the URI for every service call. + Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2019-10-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(DeploymentScriptsClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2019-10-01-preview"] = kwargs.pop("api_version", "2019-10-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_deployment_scripts_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_deployment_scripts_client.py new file mode 100644 index 0000000000000000000000000000000000000000..c74004aecc13e78f781dd9382051bc649f5cb0c3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_deployment_scripts_client.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import DeploymentScriptsClientConfiguration +from .operations import DeploymentScriptsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class DeploymentScriptsClient: # pylint: disable=client-accepts-api-version-keyword + """The APIs listed in this specification can be used to manage Deployment Scripts resource through + the Azure Resource Manager. + + :ivar deployment_scripts: DeploymentScriptsOperations operations + :vartype deployment_scripts: + azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.operations.DeploymentScriptsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: Subscription Id which forms part of the URI for every service call. + Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2019-10-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = DeploymentScriptsClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.deployment_scripts = DeploymentScriptsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "DeploymentScriptsClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0df84f5319f2e522d0fec4553e2e8b04bf904a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_vendor.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import List, cast + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..38ced0793f4166879d6ef8932a3e97f0cf1f3239 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "23.0.1" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5acf3e5d4eca01cced3e23fe61745fe24b188e02 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._deployment_scripts_client import DeploymentScriptsClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DeploymentScriptsClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..1c4c6cf61e899f55edbdb75778ae9366d32c7a00 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/_configuration.py @@ -0,0 +1,73 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class DeploymentScriptsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for DeploymentScriptsClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: Subscription Id which forms part of the URI for every service call. + Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2019-10-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(DeploymentScriptsClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2019-10-01-preview"] = kwargs.pop("api_version", "2019-10-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/_deployment_scripts_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/_deployment_scripts_client.py new file mode 100644 index 0000000000000000000000000000000000000000..729674f5b2d7b7ca6b42f5c06c174a0f5f181863 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/_deployment_scripts_client.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import DeploymentScriptsClientConfiguration +from .operations import DeploymentScriptsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class DeploymentScriptsClient: # pylint: disable=client-accepts-api-version-keyword + """The APIs listed in this specification can be used to manage Deployment Scripts resource through + the Azure Resource Manager. + + :ivar deployment_scripts: DeploymentScriptsOperations operations + :vartype deployment_scripts: + azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.aio.operations.DeploymentScriptsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: Subscription Id which forms part of the URI for every service call. + Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2019-10-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = DeploymentScriptsClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.deployment_scripts = DeploymentScriptsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "DeploymentScriptsClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3629550dcb98f22eccc765c9aa9e479a046b860e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import DeploymentScriptsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DeploymentScriptsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..5442e1fafb6a749d3095f57867a47ccb336ff421 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/operations/_operations.py @@ -0,0 +1,902 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_deployment_scripts_create_request, + build_deployment_scripts_delete_request, + build_deployment_scripts_get_logs_default_request, + build_deployment_scripts_get_logs_request, + build_deployment_scripts_get_request, + build_deployment_scripts_list_by_resource_group_request, + build_deployment_scripts_list_by_subscription_request, + build_deployment_scripts_update_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class DeploymentScriptsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.aio.DeploymentScriptsClient`'s + :attr:`deployment_scripts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def _create_initial( + self, + resource_group_name: str, + script_name: str, + deployment_script: Union[_models.DeploymentScript, IO], + **kwargs: Any + ) -> _models.DeploymentScript: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(deployment_script, (IO, bytes)): + _content = deployment_script + else: + _json = self._serialize.body(deployment_script, "DeploymentScript") + + request = build_deployment_scripts_create_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @overload + async def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: _models.DeploymentScript, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Required. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Required. + :type deployment_script: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: Union[_models.DeploymentScript, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Is either a + DeploymentScript type or a IO type. Required. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + script_name=script_name, + deployment_script=deployment_script, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DeploymentScript", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @overload + async def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[_models.DeploymentScriptUpdateParameter] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Default value + is None. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScriptUpdateParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[IO] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Default value + is None. + :type deployment_script: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[Union[_models.DeploymentScriptUpdateParameter, IO]] = None, + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Is either a + DeploymentScriptUpdateParameter type or a IO type. Default value is None. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScriptUpdateParameter + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(deployment_script, (IO, bytes)): + _content = deployment_script + else: + if deployment_script is not None: + _json = self._serialize.body(deployment_script, "DeploymentScriptUpdateParameter") + else: + _json = None + + request = build_deployment_scripts_update_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace_async + async def get(self, resource_group_name: str, script_name: str, **kwargs: Any) -> _models.DeploymentScript: + """Gets a deployment script with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, script_name: str, **kwargs: Any + ) -> None: + """Deletes a deployment script. When operation completes, status code 200 returned without + content. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_deployment_scripts_delete_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DeploymentScript"]: + """Lists all deployment scripts for a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DeploymentScript or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[_models.DeploymentScriptListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_deployment_scripts_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DeploymentScriptListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_subscription.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/deploymentScripts" + } + + @distributed_trace_async + async def get_logs(self, resource_group_name: str, script_name: str, **kwargs: Any) -> _models.ScriptLogsList: + """Gets deployment script logs for a given deployment script name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScriptLogsList or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptLogsList + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[_models.ScriptLogsList] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_logs_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_logs.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScriptLogsList", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_logs.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs" + } + + @distributed_trace_async + async def get_logs_default( + self, resource_group_name: str, script_name: str, tail: Optional[int] = None, **kwargs: Any + ) -> _models.ScriptLog: + """Gets deployment script logs for a given deployment script name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param tail: The number of lines to show from the tail of the deployment script log. Valid + value is a positive number up to 1000. If 'tail' is not provided, all available logs are shown + up to container instance log capacity of 4mb. Default value is None. + :type tail: int + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScriptLog or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptLog + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[_models.ScriptLog] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_logs_default_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + tail=tail, + api_version=api_version, + template_url=self.get_logs_default.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScriptLog", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_logs_default.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs/default" + } + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DeploymentScript"]: + """Lists deployments scripts. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DeploymentScript or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[_models.DeploymentScriptListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_deployment_scripts_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DeploymentScriptListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac22e28d5f93b66f5b0d671c8da1ff8786729690 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/__init__.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import AzureCliScript +from ._models_py3 import AzureCliScriptProperties +from ._models_py3 import AzurePowerShellScript +from ._models_py3 import AzurePowerShellScriptProperties +from ._models_py3 import AzureResourceBase +from ._models_py3 import ContainerConfiguration +from ._models_py3 import DeploymentScript +from ._models_py3 import DeploymentScriptListResult +from ._models_py3 import DeploymentScriptPropertiesBase +from ._models_py3 import DeploymentScriptUpdateParameter +from ._models_py3 import DeploymentScriptsError +from ._models_py3 import EnvironmentVariable +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorResponse +from ._models_py3 import ManagedServiceIdentity +from ._models_py3 import ScriptConfigurationBase +from ._models_py3 import ScriptLog +from ._models_py3 import ScriptLogsList +from ._models_py3 import ScriptStatus +from ._models_py3 import StorageAccountConfiguration +from ._models_py3 import SystemData +from ._models_py3 import UserAssignedIdentity + +from ._deployment_scripts_client_enums import CleanupOptions +from ._deployment_scripts_client_enums import CreatedByType +from ._deployment_scripts_client_enums import ManagedServiceIdentityType +from ._deployment_scripts_client_enums import ScriptProvisioningState +from ._deployment_scripts_client_enums import ScriptType +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureCliScript", + "AzureCliScriptProperties", + "AzurePowerShellScript", + "AzurePowerShellScriptProperties", + "AzureResourceBase", + "ContainerConfiguration", + "DeploymentScript", + "DeploymentScriptListResult", + "DeploymentScriptPropertiesBase", + "DeploymentScriptUpdateParameter", + "DeploymentScriptsError", + "EnvironmentVariable", + "ErrorAdditionalInfo", + "ErrorResponse", + "ManagedServiceIdentity", + "ScriptConfigurationBase", + "ScriptLog", + "ScriptLogsList", + "ScriptStatus", + "StorageAccountConfiguration", + "SystemData", + "UserAssignedIdentity", + "CleanupOptions", + "CreatedByType", + "ManagedServiceIdentityType", + "ScriptProvisioningState", + "ScriptType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/_deployment_scripts_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/_deployment_scripts_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..41451353e2f9b7ff949d15cd9c6cc76ee704dfef --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/_deployment_scripts_client_enums.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class CleanupOptions(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The clean up preference when the script execution gets in a terminal state. Default setting is + 'Always'. + """ + + ALWAYS = "Always" + ON_SUCCESS = "OnSuccess" + ON_EXPIRATION = "OnExpiration" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + + +class ManagedServiceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the managed identity.""" + + USER_ASSIGNED = "UserAssigned" + + +class ScriptProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """State of the script execution. This only appears in the response.""" + + CREATING = "Creating" + PROVISIONING_RESOURCES = "ProvisioningResources" + RUNNING = "Running" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + CANCELED = "Canceled" + + +class ScriptType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the script.""" + + AZURE_POWER_SHELL = "AzurePowerShell" + AZURE_CLI = "AzureCLI" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..4658c448392b7f396e2ffb9ea6cc74b884742953 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/_models_py3.py @@ -0,0 +1,1568 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class AzureResourceBase(_serialization.Model): + """Common properties for all Azure resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class DeploymentScript(AzureResourceBase): + """Deployment script object. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureCliScript, AzurePowerShellScript + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + :ivar identity: Managed identity to be used for this deployment script. Currently, only + user-assigned MSI is supported. Required. + :vartype identity: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ManagedServiceIdentity + :ivar location: The location of the ACI and the storage account for the deployment script. + Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar kind: Type of the script. Required. Known values are: "AzurePowerShell" and "AzureCLI". + :vartype kind: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptType + :ivar system_data: The system metadata related to this resource. + :vartype system_data: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "identity": {"required": True}, + "location": {"required": True}, + "kind": {"required": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + _subtype_map = {"kind": {"AzureCLI": "AzureCliScript", "AzurePowerShell": "AzurePowerShellScript"}} + + def __init__( + self, + *, + identity: "_models.ManagedServiceIdentity", + location: str, + tags: Optional[Dict[str, str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword identity: Managed identity to be used for this deployment script. Currently, only + user-assigned MSI is supported. Required. + :paramtype identity: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ManagedServiceIdentity + :keyword location: The location of the ACI and the storage account for the deployment script. + Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.identity = identity + self.location = location + self.tags = tags + self.kind: Optional[str] = None + self.system_data = None + + +class AzureCliScript(DeploymentScript): # pylint: disable=too-many-instance-attributes + """Object model for the Azure CLI script. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + :ivar identity: Managed identity to be used for this deployment script. Currently, only + user-assigned MSI is supported. Required. + :vartype identity: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ManagedServiceIdentity + :ivar location: The location of the ACI and the storage account for the deployment script. + Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar kind: Type of the script. Required. Known values are: "AzurePowerShell" and "AzureCLI". + :vartype kind: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptType + :ivar system_data: The system metadata related to this resource. + :vartype system_data: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.SystemData + :ivar container_settings: Container settings. + :vartype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ContainerConfiguration + :ivar storage_account_settings: Storage Account settings. + :vartype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.StorageAccountConfiguration + :ivar cleanup_preference: The clean up preference when the script execution gets in a terminal + state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :vartype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CleanupOptions + :ivar provisioning_state: State of the script execution. This only appears in the response. + Known values are: "Creating", "ProvisioningResources", "Running", "Succeeded", "Failed", and + "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptProvisioningState + :ivar status: Contains the results of script execution. + :vartype status: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptStatus + :ivar outputs: List of script outputs. + :vartype outputs: dict[str, JSON] + :ivar primary_script_uri: Uri for the script. This is the entry point for the external script. + :vartype primary_script_uri: str + :ivar supporting_script_uris: Supporting files for the external script. + :vartype supporting_script_uris: list[str] + :ivar script_content: Script body. + :vartype script_content: str + :ivar arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :vartype arguments: str + :ivar environment_variables: The environment variables to pass over to the script. + :vartype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.EnvironmentVariable] + :ivar force_update_tag: Gets or sets how the deployment script should be forced to execute even + if the script resource has not changed. Can be current time stamp or a GUID. + :vartype force_update_tag: str + :ivar retention_interval: Interval for which the service retains the script resource after it + reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :vartype retention_interval: ~datetime.timedelta + :ivar timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :vartype timeout: ~datetime.timedelta + :ivar az_cli_version: Azure CLI module version to be used. Required. + :vartype az_cli_version: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "identity": {"required": True}, + "location": {"required": True}, + "kind": {"required": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "status": {"readonly": True}, + "outputs": {"readonly": True}, + "script_content": {"max_length": 32000}, + "retention_interval": {"required": True}, + "az_cli_version": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "container_settings": {"key": "properties.containerSettings", "type": "ContainerConfiguration"}, + "storage_account_settings": {"key": "properties.storageAccountSettings", "type": "StorageAccountConfiguration"}, + "cleanup_preference": {"key": "properties.cleanupPreference", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "status": {"key": "properties.status", "type": "ScriptStatus"}, + "outputs": {"key": "properties.outputs", "type": "{object}"}, + "primary_script_uri": {"key": "properties.primaryScriptUri", "type": "str"}, + "supporting_script_uris": {"key": "properties.supportingScriptUris", "type": "[str]"}, + "script_content": {"key": "properties.scriptContent", "type": "str"}, + "arguments": {"key": "properties.arguments", "type": "str"}, + "environment_variables": {"key": "properties.environmentVariables", "type": "[EnvironmentVariable]"}, + "force_update_tag": {"key": "properties.forceUpdateTag", "type": "str"}, + "retention_interval": {"key": "properties.retentionInterval", "type": "duration"}, + "timeout": {"key": "properties.timeout", "type": "duration"}, + "az_cli_version": {"key": "properties.azCliVersion", "type": "str"}, + } + + def __init__( + self, + *, + identity: "_models.ManagedServiceIdentity", + location: str, + retention_interval: datetime.timedelta, + az_cli_version: str, + tags: Optional[Dict[str, str]] = None, + container_settings: Optional["_models.ContainerConfiguration"] = None, + storage_account_settings: Optional["_models.StorageAccountConfiguration"] = None, + cleanup_preference: Union[str, "_models.CleanupOptions"] = "Always", + primary_script_uri: Optional[str] = None, + supporting_script_uris: Optional[List[str]] = None, + script_content: Optional[str] = None, + arguments: Optional[str] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + force_update_tag: Optional[str] = None, + timeout: datetime.timedelta = "P1D", + **kwargs: Any + ) -> None: + """ + :keyword identity: Managed identity to be used for this deployment script. Currently, only + user-assigned MSI is supported. Required. + :paramtype identity: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ManagedServiceIdentity + :keyword location: The location of the ACI and the storage account for the deployment script. + Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword container_settings: Container settings. + :paramtype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ContainerConfiguration + :keyword storage_account_settings: Storage Account settings. + :paramtype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.StorageAccountConfiguration + :keyword cleanup_preference: The clean up preference when the script execution gets in a + terminal state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :paramtype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CleanupOptions + :keyword primary_script_uri: Uri for the script. This is the entry point for the external + script. + :paramtype primary_script_uri: str + :keyword supporting_script_uris: Supporting files for the external script. + :paramtype supporting_script_uris: list[str] + :keyword script_content: Script body. + :paramtype script_content: str + :keyword arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :paramtype arguments: str + :keyword environment_variables: The environment variables to pass over to the script. + :paramtype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.EnvironmentVariable] + :keyword force_update_tag: Gets or sets how the deployment script should be forced to execute + even if the script resource has not changed. Can be current time stamp or a GUID. + :paramtype force_update_tag: str + :keyword retention_interval: Interval for which the service retains the script resource after + it reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :paramtype retention_interval: ~datetime.timedelta + :keyword timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :paramtype timeout: ~datetime.timedelta + :keyword az_cli_version: Azure CLI module version to be used. Required. + :paramtype az_cli_version: str + """ + super().__init__(identity=identity, location=location, tags=tags, **kwargs) + self.kind: str = "AzureCLI" + self.container_settings = container_settings + self.storage_account_settings = storage_account_settings + self.cleanup_preference = cleanup_preference + self.provisioning_state = None + self.status = None + self.outputs = None + self.primary_script_uri = primary_script_uri + self.supporting_script_uris = supporting_script_uris + self.script_content = script_content + self.arguments = arguments + self.environment_variables = environment_variables + self.force_update_tag = force_update_tag + self.retention_interval = retention_interval + self.timeout = timeout + self.az_cli_version = az_cli_version + + +class ScriptConfigurationBase(_serialization.Model): + """Common configuration settings for both Azure PowerShell and Azure CLI scripts. + + All required parameters must be populated in order to send to Azure. + + :ivar primary_script_uri: Uri for the script. This is the entry point for the external script. + :vartype primary_script_uri: str + :ivar supporting_script_uris: Supporting files for the external script. + :vartype supporting_script_uris: list[str] + :ivar script_content: Script body. + :vartype script_content: str + :ivar arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :vartype arguments: str + :ivar environment_variables: The environment variables to pass over to the script. + :vartype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.EnvironmentVariable] + :ivar force_update_tag: Gets or sets how the deployment script should be forced to execute even + if the script resource has not changed. Can be current time stamp or a GUID. + :vartype force_update_tag: str + :ivar retention_interval: Interval for which the service retains the script resource after it + reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :vartype retention_interval: ~datetime.timedelta + :ivar timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :vartype timeout: ~datetime.timedelta + """ + + _validation = { + "script_content": {"max_length": 32000}, + "retention_interval": {"required": True}, + } + + _attribute_map = { + "primary_script_uri": {"key": "primaryScriptUri", "type": "str"}, + "supporting_script_uris": {"key": "supportingScriptUris", "type": "[str]"}, + "script_content": {"key": "scriptContent", "type": "str"}, + "arguments": {"key": "arguments", "type": "str"}, + "environment_variables": {"key": "environmentVariables", "type": "[EnvironmentVariable]"}, + "force_update_tag": {"key": "forceUpdateTag", "type": "str"}, + "retention_interval": {"key": "retentionInterval", "type": "duration"}, + "timeout": {"key": "timeout", "type": "duration"}, + } + + def __init__( + self, + *, + retention_interval: datetime.timedelta, + primary_script_uri: Optional[str] = None, + supporting_script_uris: Optional[List[str]] = None, + script_content: Optional[str] = None, + arguments: Optional[str] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + force_update_tag: Optional[str] = None, + timeout: datetime.timedelta = "P1D", + **kwargs: Any + ) -> None: + """ + :keyword primary_script_uri: Uri for the script. This is the entry point for the external + script. + :paramtype primary_script_uri: str + :keyword supporting_script_uris: Supporting files for the external script. + :paramtype supporting_script_uris: list[str] + :keyword script_content: Script body. + :paramtype script_content: str + :keyword arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :paramtype arguments: str + :keyword environment_variables: The environment variables to pass over to the script. + :paramtype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.EnvironmentVariable] + :keyword force_update_tag: Gets or sets how the deployment script should be forced to execute + even if the script resource has not changed. Can be current time stamp or a GUID. + :paramtype force_update_tag: str + :keyword retention_interval: Interval for which the service retains the script resource after + it reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :paramtype retention_interval: ~datetime.timedelta + :keyword timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :paramtype timeout: ~datetime.timedelta + """ + super().__init__(**kwargs) + self.primary_script_uri = primary_script_uri + self.supporting_script_uris = supporting_script_uris + self.script_content = script_content + self.arguments = arguments + self.environment_variables = environment_variables + self.force_update_tag = force_update_tag + self.retention_interval = retention_interval + self.timeout = timeout + + +class DeploymentScriptPropertiesBase(_serialization.Model): + """Common properties for the deployment script. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar container_settings: Container settings. + :vartype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ContainerConfiguration + :ivar storage_account_settings: Storage Account settings. + :vartype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.StorageAccountConfiguration + :ivar cleanup_preference: The clean up preference when the script execution gets in a terminal + state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :vartype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CleanupOptions + :ivar provisioning_state: State of the script execution. This only appears in the response. + Known values are: "Creating", "ProvisioningResources", "Running", "Succeeded", "Failed", and + "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptProvisioningState + :ivar status: Contains the results of script execution. + :vartype status: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptStatus + :ivar outputs: List of script outputs. + :vartype outputs: dict[str, JSON] + """ + + _validation = { + "provisioning_state": {"readonly": True}, + "status": {"readonly": True}, + "outputs": {"readonly": True}, + } + + _attribute_map = { + "container_settings": {"key": "containerSettings", "type": "ContainerConfiguration"}, + "storage_account_settings": {"key": "storageAccountSettings", "type": "StorageAccountConfiguration"}, + "cleanup_preference": {"key": "cleanupPreference", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "status": {"key": "status", "type": "ScriptStatus"}, + "outputs": {"key": "outputs", "type": "{object}"}, + } + + def __init__( + self, + *, + container_settings: Optional["_models.ContainerConfiguration"] = None, + storage_account_settings: Optional["_models.StorageAccountConfiguration"] = None, + cleanup_preference: Union[str, "_models.CleanupOptions"] = "Always", + **kwargs: Any + ) -> None: + """ + :keyword container_settings: Container settings. + :paramtype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ContainerConfiguration + :keyword storage_account_settings: Storage Account settings. + :paramtype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.StorageAccountConfiguration + :keyword cleanup_preference: The clean up preference when the script execution gets in a + terminal state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :paramtype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CleanupOptions + """ + super().__init__(**kwargs) + self.container_settings = container_settings + self.storage_account_settings = storage_account_settings + self.cleanup_preference = cleanup_preference + self.provisioning_state = None + self.status = None + self.outputs = None + + +class AzureCliScriptProperties( + DeploymentScriptPropertiesBase, ScriptConfigurationBase +): # pylint: disable=too-many-instance-attributes + """Properties of the Azure CLI script object. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar primary_script_uri: Uri for the script. This is the entry point for the external script. + :vartype primary_script_uri: str + :ivar supporting_script_uris: Supporting files for the external script. + :vartype supporting_script_uris: list[str] + :ivar script_content: Script body. + :vartype script_content: str + :ivar arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :vartype arguments: str + :ivar environment_variables: The environment variables to pass over to the script. + :vartype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.EnvironmentVariable] + :ivar force_update_tag: Gets or sets how the deployment script should be forced to execute even + if the script resource has not changed. Can be current time stamp or a GUID. + :vartype force_update_tag: str + :ivar retention_interval: Interval for which the service retains the script resource after it + reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :vartype retention_interval: ~datetime.timedelta + :ivar timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :vartype timeout: ~datetime.timedelta + :ivar container_settings: Container settings. + :vartype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ContainerConfiguration + :ivar storage_account_settings: Storage Account settings. + :vartype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.StorageAccountConfiguration + :ivar cleanup_preference: The clean up preference when the script execution gets in a terminal + state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :vartype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CleanupOptions + :ivar provisioning_state: State of the script execution. This only appears in the response. + Known values are: "Creating", "ProvisioningResources", "Running", "Succeeded", "Failed", and + "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptProvisioningState + :ivar status: Contains the results of script execution. + :vartype status: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptStatus + :ivar outputs: List of script outputs. + :vartype outputs: dict[str, JSON] + :ivar az_cli_version: Azure CLI module version to be used. Required. + :vartype az_cli_version: str + """ + + _validation = { + "script_content": {"max_length": 32000}, + "retention_interval": {"required": True}, + "provisioning_state": {"readonly": True}, + "status": {"readonly": True}, + "outputs": {"readonly": True}, + "az_cli_version": {"required": True}, + } + + _attribute_map = { + "primary_script_uri": {"key": "primaryScriptUri", "type": "str"}, + "supporting_script_uris": {"key": "supportingScriptUris", "type": "[str]"}, + "script_content": {"key": "scriptContent", "type": "str"}, + "arguments": {"key": "arguments", "type": "str"}, + "environment_variables": {"key": "environmentVariables", "type": "[EnvironmentVariable]"}, + "force_update_tag": {"key": "forceUpdateTag", "type": "str"}, + "retention_interval": {"key": "retentionInterval", "type": "duration"}, + "timeout": {"key": "timeout", "type": "duration"}, + "container_settings": {"key": "containerSettings", "type": "ContainerConfiguration"}, + "storage_account_settings": {"key": "storageAccountSettings", "type": "StorageAccountConfiguration"}, + "cleanup_preference": {"key": "cleanupPreference", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "status": {"key": "status", "type": "ScriptStatus"}, + "outputs": {"key": "outputs", "type": "{object}"}, + "az_cli_version": {"key": "azCliVersion", "type": "str"}, + } + + def __init__( + self, + *, + retention_interval: datetime.timedelta, + az_cli_version: str, + primary_script_uri: Optional[str] = None, + supporting_script_uris: Optional[List[str]] = None, + script_content: Optional[str] = None, + arguments: Optional[str] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + force_update_tag: Optional[str] = None, + timeout: datetime.timedelta = "P1D", + container_settings: Optional["_models.ContainerConfiguration"] = None, + storage_account_settings: Optional["_models.StorageAccountConfiguration"] = None, + cleanup_preference: Union[str, "_models.CleanupOptions"] = "Always", + **kwargs: Any + ) -> None: + """ + :keyword primary_script_uri: Uri for the script. This is the entry point for the external + script. + :paramtype primary_script_uri: str + :keyword supporting_script_uris: Supporting files for the external script. + :paramtype supporting_script_uris: list[str] + :keyword script_content: Script body. + :paramtype script_content: str + :keyword arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :paramtype arguments: str + :keyword environment_variables: The environment variables to pass over to the script. + :paramtype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.EnvironmentVariable] + :keyword force_update_tag: Gets or sets how the deployment script should be forced to execute + even if the script resource has not changed. Can be current time stamp or a GUID. + :paramtype force_update_tag: str + :keyword retention_interval: Interval for which the service retains the script resource after + it reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :paramtype retention_interval: ~datetime.timedelta + :keyword timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :paramtype timeout: ~datetime.timedelta + :keyword container_settings: Container settings. + :paramtype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ContainerConfiguration + :keyword storage_account_settings: Storage Account settings. + :paramtype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.StorageAccountConfiguration + :keyword cleanup_preference: The clean up preference when the script execution gets in a + terminal state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :paramtype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CleanupOptions + :keyword az_cli_version: Azure CLI module version to be used. Required. + :paramtype az_cli_version: str + """ + super().__init__( + container_settings=container_settings, + storage_account_settings=storage_account_settings, + cleanup_preference=cleanup_preference, + primary_script_uri=primary_script_uri, + supporting_script_uris=supporting_script_uris, + script_content=script_content, + arguments=arguments, + environment_variables=environment_variables, + force_update_tag=force_update_tag, + retention_interval=retention_interval, + timeout=timeout, + **kwargs + ) + self.primary_script_uri = primary_script_uri + self.supporting_script_uris = supporting_script_uris + self.script_content = script_content + self.arguments = arguments + self.environment_variables = environment_variables + self.force_update_tag = force_update_tag + self.retention_interval = retention_interval + self.timeout = timeout + self.az_cli_version = az_cli_version + self.container_settings = container_settings + self.storage_account_settings = storage_account_settings + self.cleanup_preference = cleanup_preference + self.provisioning_state = None + self.status = None + self.outputs = None + + +class AzurePowerShellScript(DeploymentScript): # pylint: disable=too-many-instance-attributes + """Object model for the Azure PowerShell script. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + :ivar identity: Managed identity to be used for this deployment script. Currently, only + user-assigned MSI is supported. Required. + :vartype identity: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ManagedServiceIdentity + :ivar location: The location of the ACI and the storage account for the deployment script. + Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar kind: Type of the script. Required. Known values are: "AzurePowerShell" and "AzureCLI". + :vartype kind: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptType + :ivar system_data: The system metadata related to this resource. + :vartype system_data: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.SystemData + :ivar container_settings: Container settings. + :vartype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ContainerConfiguration + :ivar storage_account_settings: Storage Account settings. + :vartype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.StorageAccountConfiguration + :ivar cleanup_preference: The clean up preference when the script execution gets in a terminal + state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :vartype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CleanupOptions + :ivar provisioning_state: State of the script execution. This only appears in the response. + Known values are: "Creating", "ProvisioningResources", "Running", "Succeeded", "Failed", and + "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptProvisioningState + :ivar status: Contains the results of script execution. + :vartype status: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptStatus + :ivar outputs: List of script outputs. + :vartype outputs: dict[str, JSON] + :ivar primary_script_uri: Uri for the script. This is the entry point for the external script. + :vartype primary_script_uri: str + :ivar supporting_script_uris: Supporting files for the external script. + :vartype supporting_script_uris: list[str] + :ivar script_content: Script body. + :vartype script_content: str + :ivar arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :vartype arguments: str + :ivar environment_variables: The environment variables to pass over to the script. + :vartype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.EnvironmentVariable] + :ivar force_update_tag: Gets or sets how the deployment script should be forced to execute even + if the script resource has not changed. Can be current time stamp or a GUID. + :vartype force_update_tag: str + :ivar retention_interval: Interval for which the service retains the script resource after it + reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :vartype retention_interval: ~datetime.timedelta + :ivar timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :vartype timeout: ~datetime.timedelta + :ivar az_power_shell_version: Azure PowerShell module version to be used. Required. + :vartype az_power_shell_version: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "identity": {"required": True}, + "location": {"required": True}, + "kind": {"required": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "status": {"readonly": True}, + "outputs": {"readonly": True}, + "script_content": {"max_length": 32000}, + "retention_interval": {"required": True}, + "az_power_shell_version": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "container_settings": {"key": "properties.containerSettings", "type": "ContainerConfiguration"}, + "storage_account_settings": {"key": "properties.storageAccountSettings", "type": "StorageAccountConfiguration"}, + "cleanup_preference": {"key": "properties.cleanupPreference", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "status": {"key": "properties.status", "type": "ScriptStatus"}, + "outputs": {"key": "properties.outputs", "type": "{object}"}, + "primary_script_uri": {"key": "properties.primaryScriptUri", "type": "str"}, + "supporting_script_uris": {"key": "properties.supportingScriptUris", "type": "[str]"}, + "script_content": {"key": "properties.scriptContent", "type": "str"}, + "arguments": {"key": "properties.arguments", "type": "str"}, + "environment_variables": {"key": "properties.environmentVariables", "type": "[EnvironmentVariable]"}, + "force_update_tag": {"key": "properties.forceUpdateTag", "type": "str"}, + "retention_interval": {"key": "properties.retentionInterval", "type": "duration"}, + "timeout": {"key": "properties.timeout", "type": "duration"}, + "az_power_shell_version": {"key": "properties.azPowerShellVersion", "type": "str"}, + } + + def __init__( + self, + *, + identity: "_models.ManagedServiceIdentity", + location: str, + retention_interval: datetime.timedelta, + az_power_shell_version: str, + tags: Optional[Dict[str, str]] = None, + container_settings: Optional["_models.ContainerConfiguration"] = None, + storage_account_settings: Optional["_models.StorageAccountConfiguration"] = None, + cleanup_preference: Union[str, "_models.CleanupOptions"] = "Always", + primary_script_uri: Optional[str] = None, + supporting_script_uris: Optional[List[str]] = None, + script_content: Optional[str] = None, + arguments: Optional[str] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + force_update_tag: Optional[str] = None, + timeout: datetime.timedelta = "P1D", + **kwargs: Any + ) -> None: + """ + :keyword identity: Managed identity to be used for this deployment script. Currently, only + user-assigned MSI is supported. Required. + :paramtype identity: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ManagedServiceIdentity + :keyword location: The location of the ACI and the storage account for the deployment script. + Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword container_settings: Container settings. + :paramtype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ContainerConfiguration + :keyword storage_account_settings: Storage Account settings. + :paramtype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.StorageAccountConfiguration + :keyword cleanup_preference: The clean up preference when the script execution gets in a + terminal state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :paramtype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CleanupOptions + :keyword primary_script_uri: Uri for the script. This is the entry point for the external + script. + :paramtype primary_script_uri: str + :keyword supporting_script_uris: Supporting files for the external script. + :paramtype supporting_script_uris: list[str] + :keyword script_content: Script body. + :paramtype script_content: str + :keyword arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :paramtype arguments: str + :keyword environment_variables: The environment variables to pass over to the script. + :paramtype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.EnvironmentVariable] + :keyword force_update_tag: Gets or sets how the deployment script should be forced to execute + even if the script resource has not changed. Can be current time stamp or a GUID. + :paramtype force_update_tag: str + :keyword retention_interval: Interval for which the service retains the script resource after + it reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :paramtype retention_interval: ~datetime.timedelta + :keyword timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :paramtype timeout: ~datetime.timedelta + :keyword az_power_shell_version: Azure PowerShell module version to be used. Required. + :paramtype az_power_shell_version: str + """ + super().__init__(identity=identity, location=location, tags=tags, **kwargs) + self.kind: str = "AzurePowerShell" + self.container_settings = container_settings + self.storage_account_settings = storage_account_settings + self.cleanup_preference = cleanup_preference + self.provisioning_state = None + self.status = None + self.outputs = None + self.primary_script_uri = primary_script_uri + self.supporting_script_uris = supporting_script_uris + self.script_content = script_content + self.arguments = arguments + self.environment_variables = environment_variables + self.force_update_tag = force_update_tag + self.retention_interval = retention_interval + self.timeout = timeout + self.az_power_shell_version = az_power_shell_version + + +class AzurePowerShellScriptProperties( + DeploymentScriptPropertiesBase, ScriptConfigurationBase +): # pylint: disable=too-many-instance-attributes + """Properties of the Azure PowerShell script object. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar primary_script_uri: Uri for the script. This is the entry point for the external script. + :vartype primary_script_uri: str + :ivar supporting_script_uris: Supporting files for the external script. + :vartype supporting_script_uris: list[str] + :ivar script_content: Script body. + :vartype script_content: str + :ivar arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :vartype arguments: str + :ivar environment_variables: The environment variables to pass over to the script. + :vartype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.EnvironmentVariable] + :ivar force_update_tag: Gets or sets how the deployment script should be forced to execute even + if the script resource has not changed. Can be current time stamp or a GUID. + :vartype force_update_tag: str + :ivar retention_interval: Interval for which the service retains the script resource after it + reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :vartype retention_interval: ~datetime.timedelta + :ivar timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :vartype timeout: ~datetime.timedelta + :ivar container_settings: Container settings. + :vartype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ContainerConfiguration + :ivar storage_account_settings: Storage Account settings. + :vartype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.StorageAccountConfiguration + :ivar cleanup_preference: The clean up preference when the script execution gets in a terminal + state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :vartype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CleanupOptions + :ivar provisioning_state: State of the script execution. This only appears in the response. + Known values are: "Creating", "ProvisioningResources", "Running", "Succeeded", "Failed", and + "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptProvisioningState + :ivar status: Contains the results of script execution. + :vartype status: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptStatus + :ivar outputs: List of script outputs. + :vartype outputs: dict[str, JSON] + :ivar az_power_shell_version: Azure PowerShell module version to be used. Required. + :vartype az_power_shell_version: str + """ + + _validation = { + "script_content": {"max_length": 32000}, + "retention_interval": {"required": True}, + "provisioning_state": {"readonly": True}, + "status": {"readonly": True}, + "outputs": {"readonly": True}, + "az_power_shell_version": {"required": True}, + } + + _attribute_map = { + "primary_script_uri": {"key": "primaryScriptUri", "type": "str"}, + "supporting_script_uris": {"key": "supportingScriptUris", "type": "[str]"}, + "script_content": {"key": "scriptContent", "type": "str"}, + "arguments": {"key": "arguments", "type": "str"}, + "environment_variables": {"key": "environmentVariables", "type": "[EnvironmentVariable]"}, + "force_update_tag": {"key": "forceUpdateTag", "type": "str"}, + "retention_interval": {"key": "retentionInterval", "type": "duration"}, + "timeout": {"key": "timeout", "type": "duration"}, + "container_settings": {"key": "containerSettings", "type": "ContainerConfiguration"}, + "storage_account_settings": {"key": "storageAccountSettings", "type": "StorageAccountConfiguration"}, + "cleanup_preference": {"key": "cleanupPreference", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "status": {"key": "status", "type": "ScriptStatus"}, + "outputs": {"key": "outputs", "type": "{object}"}, + "az_power_shell_version": {"key": "azPowerShellVersion", "type": "str"}, + } + + def __init__( + self, + *, + retention_interval: datetime.timedelta, + az_power_shell_version: str, + primary_script_uri: Optional[str] = None, + supporting_script_uris: Optional[List[str]] = None, + script_content: Optional[str] = None, + arguments: Optional[str] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + force_update_tag: Optional[str] = None, + timeout: datetime.timedelta = "P1D", + container_settings: Optional["_models.ContainerConfiguration"] = None, + storage_account_settings: Optional["_models.StorageAccountConfiguration"] = None, + cleanup_preference: Union[str, "_models.CleanupOptions"] = "Always", + **kwargs: Any + ) -> None: + """ + :keyword primary_script_uri: Uri for the script. This is the entry point for the external + script. + :paramtype primary_script_uri: str + :keyword supporting_script_uris: Supporting files for the external script. + :paramtype supporting_script_uris: list[str] + :keyword script_content: Script body. + :paramtype script_content: str + :keyword arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :paramtype arguments: str + :keyword environment_variables: The environment variables to pass over to the script. + :paramtype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.EnvironmentVariable] + :keyword force_update_tag: Gets or sets how the deployment script should be forced to execute + even if the script resource has not changed. Can be current time stamp or a GUID. + :paramtype force_update_tag: str + :keyword retention_interval: Interval for which the service retains the script resource after + it reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :paramtype retention_interval: ~datetime.timedelta + :keyword timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :paramtype timeout: ~datetime.timedelta + :keyword container_settings: Container settings. + :paramtype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ContainerConfiguration + :keyword storage_account_settings: Storage Account settings. + :paramtype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.StorageAccountConfiguration + :keyword cleanup_preference: The clean up preference when the script execution gets in a + terminal state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :paramtype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CleanupOptions + :keyword az_power_shell_version: Azure PowerShell module version to be used. Required. + :paramtype az_power_shell_version: str + """ + super().__init__( + container_settings=container_settings, + storage_account_settings=storage_account_settings, + cleanup_preference=cleanup_preference, + primary_script_uri=primary_script_uri, + supporting_script_uris=supporting_script_uris, + script_content=script_content, + arguments=arguments, + environment_variables=environment_variables, + force_update_tag=force_update_tag, + retention_interval=retention_interval, + timeout=timeout, + **kwargs + ) + self.primary_script_uri = primary_script_uri + self.supporting_script_uris = supporting_script_uris + self.script_content = script_content + self.arguments = arguments + self.environment_variables = environment_variables + self.force_update_tag = force_update_tag + self.retention_interval = retention_interval + self.timeout = timeout + self.az_power_shell_version = az_power_shell_version + self.container_settings = container_settings + self.storage_account_settings = storage_account_settings + self.cleanup_preference = cleanup_preference + self.provisioning_state = None + self.status = None + self.outputs = None + + +class ContainerConfiguration(_serialization.Model): + """Settings to customize ACI container instance. + + :ivar container_group_name: Container group name, if not specified then the name will get + auto-generated. Not specifying a 'containerGroupName' indicates the system to generate a unique + name which might end up flagging an Azure Policy as non-compliant. Use 'containerGroupName' + when you have an Azure Policy that expects a specific naming convention or when you want to + fully control the name. 'containerGroupName' property must be between 1 and 63 characters long, + must contain only lowercase letters, numbers, and dashes and it cannot start or end with a dash + and consecutive dashes are not allowed. To specify a 'containerGroupName', add the following + object to properties: { "containerSettings": { "containerGroupName": "contoso-container" } }. + If you do not want to specify a 'containerGroupName' then do not add 'containerSettings' + property. + :vartype container_group_name: str + """ + + _validation = { + "container_group_name": {"max_length": 63, "min_length": 1}, + } + + _attribute_map = { + "container_group_name": {"key": "containerGroupName", "type": "str"}, + } + + def __init__(self, *, container_group_name: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword container_group_name: Container group name, if not specified then the name will get + auto-generated. Not specifying a 'containerGroupName' indicates the system to generate a unique + name which might end up flagging an Azure Policy as non-compliant. Use 'containerGroupName' + when you have an Azure Policy that expects a specific naming convention or when you want to + fully control the name. 'containerGroupName' property must be between 1 and 63 characters long, + must contain only lowercase letters, numbers, and dashes and it cannot start or end with a dash + and consecutive dashes are not allowed. To specify a 'containerGroupName', add the following + object to properties: { "containerSettings": { "containerGroupName": "contoso-container" } }. + If you do not want to specify a 'containerGroupName' then do not add 'containerSettings' + property. + :paramtype container_group_name: str + """ + super().__init__(**kwargs) + self.container_group_name = container_group_name + + +class DeploymentScriptListResult(_serialization.Model): + """List of deployment scripts. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: An array of deployment scripts. + :vartype value: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _validation = { + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[DeploymentScript]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[List["_models.DeploymentScript"]] = None, **kwargs: Any) -> None: + """ + :keyword value: An array of deployment scripts. + :paramtype value: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + """ + super().__init__(**kwargs) + self.value = value + self.next_link = None + + +class DeploymentScriptsError(_serialization.Model): + """Deployment scripts error response. + + :ivar error: Common error response for all Azure Resource Manager APIs to return error details + for failed operations. (This also follows the OData error response format.). + :vartype error: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ErrorResponse + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorResponse"}, + } + + def __init__(self, *, error: Optional["_models.ErrorResponse"] = None, **kwargs: Any) -> None: + """ + :keyword error: Common error response for all Azure Resource Manager APIs to return error + details for failed operations. (This also follows the OData error response format.). + :paramtype error: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ErrorResponse + """ + super().__init__(**kwargs) + self.error = error + + +class DeploymentScriptUpdateParameter(AzureResourceBase): + """Deployment script parameters to be updated. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + :ivar tags: Resource tags to be updated. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Resource tags to be updated. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.tags = tags + + +class EnvironmentVariable(_serialization.Model): + """The environment variable to pass to the script in the container instance. + + All required parameters must be populated in order to send to Azure. + + :ivar name: The name of the environment variable. Required. + :vartype name: str + :ivar value: The value of the environment variable. + :vartype value: str + :ivar secure_value: The value of the secure environment variable. + :vartype secure_value: str + """ + + _validation = { + "name": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, + "secure_value": {"key": "secureValue", "type": "str"}, + } + + def __init__( + self, *, name: str, value: Optional[str] = None, secure_value: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword name: The name of the environment variable. Required. + :paramtype name: str + :keyword value: The value of the environment variable. + :paramtype value: str + :keyword secure_value: The value of the secure environment variable. + :paramtype secure_value: str + """ + super().__init__(**kwargs) + self.name = name + self.value = value + self.secure_value = secure_value + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorResponse]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ManagedServiceIdentity(_serialization.Model): + """Managed identity generic object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: Type of the managed identity. "UserAssigned" + :vartype type: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ManagedServiceIdentityType + :ivar tenant_id: ID of the Azure Active Directory. + :vartype tenant_id: str + :ivar user_assigned_identities: The list of user-assigned managed identities associated with + the resource. Key is the Azure resource Id of the managed identity. + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.UserAssignedIdentity] + """ + + _validation = { + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentity}"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.ManagedServiceIdentityType"]] = None, + user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentity"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: Type of the managed identity. "UserAssigned" + :paramtype type: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ManagedServiceIdentityType + :keyword user_assigned_identities: The list of user-assigned managed identities associated with + the resource. Key is the Azure resource Id of the managed identity. + :paramtype user_assigned_identities: dict[str, + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.UserAssignedIdentity] + """ + super().__init__(**kwargs) + self.type = type + self.tenant_id = None + self.user_assigned_identities = user_assigned_identities + + +class ScriptLog(AzureResourceBase): + """Script execution log object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + :ivar log: Script execution logs in text format. + :vartype log: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "log": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "log": {"key": "properties.log", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.log = None + + +class ScriptLogsList(_serialization.Model): + """Deployment script execution logs. + + :ivar value: Deployment scripts logs. + :vartype value: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptLog] + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ScriptLog]"}, + } + + def __init__(self, *, value: Optional[List["_models.ScriptLog"]] = None, **kwargs: Any) -> None: + """ + :keyword value: Deployment scripts logs. + :paramtype value: + list[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptLog] + """ + super().__init__(**kwargs) + self.value = value + + +class ScriptStatus(_serialization.Model): + """Generic object modeling results of script execution. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar container_instance_id: ACI resource Id. + :vartype container_instance_id: str + :ivar storage_account_id: Storage account resource Id. + :vartype storage_account_id: str + :ivar start_time: Start time of the script execution. + :vartype start_time: ~datetime.datetime + :ivar end_time: End time of the script execution. + :vartype end_time: ~datetime.datetime + :ivar expiration_time: Time the deployment script resource will expire. + :vartype expiration_time: ~datetime.datetime + :ivar error: Error that is relayed from the script execution. + :vartype error: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ErrorResponse + """ + + _validation = { + "container_instance_id": {"readonly": True}, + "storage_account_id": {"readonly": True}, + "start_time": {"readonly": True}, + "end_time": {"readonly": True}, + "expiration_time": {"readonly": True}, + } + + _attribute_map = { + "container_instance_id": {"key": "containerInstanceId", "type": "str"}, + "storage_account_id": {"key": "storageAccountId", "type": "str"}, + "start_time": {"key": "startTime", "type": "iso-8601"}, + "end_time": {"key": "endTime", "type": "iso-8601"}, + "expiration_time": {"key": "expirationTime", "type": "iso-8601"}, + "error": {"key": "error", "type": "ErrorResponse"}, + } + + def __init__(self, *, error: Optional["_models.ErrorResponse"] = None, **kwargs: Any) -> None: + """ + :keyword error: Error that is relayed from the script execution. + :paramtype error: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ErrorResponse + """ + super().__init__(**kwargs) + self.container_instance_id = None + self.storage_account_id = None + self.start_time = None + self.end_time = None + self.expiration_time = None + self.error = error + + +class StorageAccountConfiguration(_serialization.Model): + """Settings to use an existing storage account. Valid storage account kinds are: Storage, + StorageV2 and FileStorage. + + :ivar storage_account_name: The storage account name. + :vartype storage_account_name: str + :ivar storage_account_key: The storage account access key. + :vartype storage_account_key: str + """ + + _attribute_map = { + "storage_account_name": {"key": "storageAccountName", "type": "str"}, + "storage_account_key": {"key": "storageAccountKey", "type": "str"}, + } + + def __init__( + self, *, storage_account_name: Optional[str] = None, storage_account_key: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword storage_account_name: The storage account name. + :paramtype storage_account_name: str + :keyword storage_account_key: The storage account access key. + :paramtype storage_account_key: str + """ + super().__init__(**kwargs) + self.storage_account_name = storage_account_name + self.storage_account_key = storage_account_key + + +class SystemData(_serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + } + + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword created_by: The identity that created the resource. + :paramtype created_by: str + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :paramtype created_by_type: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CreatedByType + :keyword created_at: The timestamp of resource creation (UTC). + :paramtype created_at: ~datetime.datetime + :keyword last_modified_by: The identity that last modified the resource. + :paramtype last_modified_by: str + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". + :paramtype last_modified_by_type: str or + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.CreatedByType + :keyword last_modified_at: The timestamp of resource last modification (UTC). + :paramtype last_modified_at: ~datetime.datetime + """ + super().__init__(**kwargs) + self.created_by = created_by + self.created_by_type = created_by_type + self.created_at = created_at + self.last_modified_by = last_modified_by + self.last_modified_by_type = last_modified_by_type + self.last_modified_at = last_modified_at + + +class UserAssignedIdentity(_serialization.Model): + """User-assigned managed identity. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: Azure Active Directory principal ID associated with this identity. + :vartype principal_id: str + :ivar client_id: Client App Id associated with this identity. + :vartype client_id: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.principal_id = None + self.client_id = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3629550dcb98f22eccc765c9aa9e479a046b860e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import DeploymentScriptsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DeploymentScriptsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..4821d49ce85a7693770030f7ca1bc3501627b193 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/operations/_operations.py @@ -0,0 +1,1171 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_deployment_scripts_create_request( + resource_group_name: str, script_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_update_request( + resource_group_name: str, script_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_get_request( + resource_group_name: str, script_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_delete_request( + resource_group_name: str, script_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/deploymentScripts") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_get_logs_request( + resource_group_name: str, script_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_get_logs_default_request( + resource_group_name: str, script_name: str, subscription_id: str, *, tail: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tail is not None: + _params["tail"] = _SERIALIZER.query("tail", tail, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_list_by_resource_group_request( + resource_group_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DeploymentScriptsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.DeploymentScriptsClient`'s + :attr:`deployment_scripts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def _create_initial( + self, + resource_group_name: str, + script_name: str, + deployment_script: Union[_models.DeploymentScript, IO], + **kwargs: Any + ) -> _models.DeploymentScript: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(deployment_script, (IO, bytes)): + _content = deployment_script + else: + _json = self._serialize.body(deployment_script, "DeploymentScript") + + request = build_deployment_scripts_create_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @overload + def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: _models.DeploymentScript, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Required. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Required. + :type deployment_script: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: Union[_models.DeploymentScript, IO], + **kwargs: Any + ) -> LROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Is either a + DeploymentScript type or a IO type. Required. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + script_name=script_name, + deployment_script=deployment_script, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DeploymentScript", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @overload + def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[_models.DeploymentScriptUpdateParameter] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Default value + is None. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScriptUpdateParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[IO] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Default value + is None. + :type deployment_script: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[Union[_models.DeploymentScriptUpdateParameter, IO]] = None, + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Is either a + DeploymentScriptUpdateParameter type or a IO type. Default value is None. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScriptUpdateParameter + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(deployment_script, (IO, bytes)): + _content = deployment_script + else: + if deployment_script is not None: + _json = self._serialize.body(deployment_script, "DeploymentScriptUpdateParameter") + else: + _json = None + + request = build_deployment_scripts_update_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace + def get(self, resource_group_name: str, script_name: str, **kwargs: Any) -> _models.DeploymentScript: + """Gets a deployment script with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, script_name: str, **kwargs: Any + ) -> None: + """Deletes a deployment script. When operation completes, status code 200 returned without + content. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_deployment_scripts_delete_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DeploymentScript"]: + """Lists all deployment scripts for a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DeploymentScript or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[_models.DeploymentScriptListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_deployment_scripts_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DeploymentScriptListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_subscription.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/deploymentScripts" + } + + @distributed_trace + def get_logs(self, resource_group_name: str, script_name: str, **kwargs: Any) -> _models.ScriptLogsList: + """Gets deployment script logs for a given deployment script name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScriptLogsList or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptLogsList + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[_models.ScriptLogsList] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_logs_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_logs.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScriptLogsList", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_logs.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs" + } + + @distributed_trace + def get_logs_default( + self, resource_group_name: str, script_name: str, tail: Optional[int] = None, **kwargs: Any + ) -> _models.ScriptLog: + """Gets deployment script logs for a given deployment script name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param tail: The number of lines to show from the tail of the deployment script log. Valid + value is a positive number up to 1000. If 'tail' is not provided, all available logs are shown + up to container instance log capacity of 4mb. Default value is None. + :type tail: int + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScriptLog or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.ScriptLog + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[_models.ScriptLog] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_logs_default_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + tail=tail, + api_version=api_version, + template_url=self.get_logs_default.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScriptLog", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_logs_default.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs/default" + } + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.DeploymentScript"]: + """Lists deployments scripts. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DeploymentScript or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.deploymentscripts.v2019_10_01_preview.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2019-10-01-preview") + ) + cls: ClsType[_models.DeploymentScriptListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_deployment_scripts_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DeploymentScriptListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2019_10_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b746eedf3a2f31d113774a3abf6adb83ed943354 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._deployment_scripts_client import DeploymentScriptsClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DeploymentScriptsClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..c29cbc4456e9d1de3a39d7f6518f8b7b1f1afaed --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_configuration.py @@ -0,0 +1,73 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class DeploymentScriptsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for DeploymentScriptsClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: Subscription Id which forms part of the URI for every service call. + Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2020-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(DeploymentScriptsClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", "2020-10-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_deployment_scripts_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_deployment_scripts_client.py new file mode 100644 index 0000000000000000000000000000000000000000..cdcdafc494512551ea6eb40a5f3c33c2c0d39a03 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_deployment_scripts_client.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import DeploymentScriptsClientConfiguration +from .operations import DeploymentScriptsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class DeploymentScriptsClient: # pylint: disable=client-accepts-api-version-keyword + """The APIs listed in this specification can be used to manage Deployment Scripts resource through + the Azure Resource Manager. + + :ivar deployment_scripts: DeploymentScriptsOperations operations + :vartype deployment_scripts: + azure.mgmt.resource.deploymentscripts.v2020_10_01.operations.DeploymentScriptsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: Subscription Id which forms part of the URI for every service call. + Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2020-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = DeploymentScriptsClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.deployment_scripts = DeploymentScriptsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "DeploymentScriptsClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0df84f5319f2e522d0fec4553e2e8b04bf904a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_vendor.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import List, cast + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..38ced0793f4166879d6ef8932a3e97f0cf1f3239 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "23.0.1" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5acf3e5d4eca01cced3e23fe61745fe24b188e02 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._deployment_scripts_client import DeploymentScriptsClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DeploymentScriptsClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..b08fea9ae2474a2a09b132e49074022b473b933b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/_configuration.py @@ -0,0 +1,73 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class DeploymentScriptsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for DeploymentScriptsClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: Subscription Id which forms part of the URI for every service call. + Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2020-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(DeploymentScriptsClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", "2020-10-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/_deployment_scripts_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/_deployment_scripts_client.py new file mode 100644 index 0000000000000000000000000000000000000000..abcc4728bcc1022294353d7a35448170e7d456da --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/_deployment_scripts_client.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import DeploymentScriptsClientConfiguration +from .operations import DeploymentScriptsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class DeploymentScriptsClient: # pylint: disable=client-accepts-api-version-keyword + """The APIs listed in this specification can be used to manage Deployment Scripts resource through + the Azure Resource Manager. + + :ivar deployment_scripts: DeploymentScriptsOperations operations + :vartype deployment_scripts: + azure.mgmt.resource.deploymentscripts.v2020_10_01.aio.operations.DeploymentScriptsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: Subscription Id which forms part of the URI for every service call. + Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2020-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = DeploymentScriptsClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.deployment_scripts = DeploymentScriptsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "DeploymentScriptsClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3629550dcb98f22eccc765c9aa9e479a046b860e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import DeploymentScriptsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DeploymentScriptsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..eb2f97d24d37b81f00b4998ce02be8e92fd0bb38 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/operations/_operations.py @@ -0,0 +1,883 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_deployment_scripts_create_request, + build_deployment_scripts_delete_request, + build_deployment_scripts_get_logs_default_request, + build_deployment_scripts_get_logs_request, + build_deployment_scripts_get_request, + build_deployment_scripts_list_by_resource_group_request, + build_deployment_scripts_list_by_subscription_request, + build_deployment_scripts_update_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class DeploymentScriptsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.deploymentscripts.v2020_10_01.aio.DeploymentScriptsClient`'s + :attr:`deployment_scripts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def _create_initial( + self, + resource_group_name: str, + script_name: str, + deployment_script: Union[_models.DeploymentScript, IO], + **kwargs: Any + ) -> _models.DeploymentScript: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(deployment_script, (IO, bytes)): + _content = deployment_script + else: + _json = self._serialize.body(deployment_script, "DeploymentScript") + + request = build_deployment_scripts_create_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @overload + async def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: _models.DeploymentScript, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Required. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Required. + :type deployment_script: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: Union[_models.DeploymentScript, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Is either a + DeploymentScript type or a IO type. Required. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + script_name=script_name, + deployment_script=deployment_script, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DeploymentScript", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @overload + async def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[_models.DeploymentScriptUpdateParameter] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Default value + is None. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScriptUpdateParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[IO] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Default value + is None. + :type deployment_script: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[Union[_models.DeploymentScriptUpdateParameter, IO]] = None, + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Is either a + DeploymentScriptUpdateParameter type or a IO type. Default value is None. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScriptUpdateParameter or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(deployment_script, (IO, bytes)): + _content = deployment_script + else: + if deployment_script is not None: + _json = self._serialize.body(deployment_script, "DeploymentScriptUpdateParameter") + else: + _json = None + + request = build_deployment_scripts_update_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace_async + async def get(self, resource_group_name: str, script_name: str, **kwargs: Any) -> _models.DeploymentScript: + """Gets a deployment script with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, script_name: str, **kwargs: Any + ) -> None: + """Deletes a deployment script. When operation completes, status code 200 returned without + content. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_deployment_scripts_delete_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DeploymentScript"]: + """Lists all deployment scripts for a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DeploymentScript or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[_models.DeploymentScriptListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_deployment_scripts_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DeploymentScriptListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_subscription.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/deploymentScripts" + } + + @distributed_trace_async + async def get_logs(self, resource_group_name: str, script_name: str, **kwargs: Any) -> _models.ScriptLogsList: + """Gets deployment script logs for a given deployment script name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScriptLogsList or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptLogsList + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[_models.ScriptLogsList] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_logs_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_logs.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScriptLogsList", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_logs.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs" + } + + @distributed_trace_async + async def get_logs_default( + self, resource_group_name: str, script_name: str, tail: Optional[int] = None, **kwargs: Any + ) -> _models.ScriptLog: + """Gets deployment script logs for a given deployment script name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param tail: The number of lines to show from the tail of the deployment script log. Valid + value is a positive number up to 1000. If 'tail' is not provided, all available logs are shown + up to container instance log capacity of 4mb. Default value is None. + :type tail: int + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScriptLog or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptLog + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[_models.ScriptLog] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_logs_default_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + tail=tail, + api_version=api_version, + template_url=self.get_logs_default.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScriptLog", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_logs_default.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs/default" + } + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DeploymentScript"]: + """Lists deployments scripts. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DeploymentScript or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[_models.DeploymentScriptListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_deployment_scripts_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DeploymentScriptListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac22e28d5f93b66f5b0d671c8da1ff8786729690 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/__init__.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import AzureCliScript +from ._models_py3 import AzureCliScriptProperties +from ._models_py3 import AzurePowerShellScript +from ._models_py3 import AzurePowerShellScriptProperties +from ._models_py3 import AzureResourceBase +from ._models_py3 import ContainerConfiguration +from ._models_py3 import DeploymentScript +from ._models_py3 import DeploymentScriptListResult +from ._models_py3 import DeploymentScriptPropertiesBase +from ._models_py3 import DeploymentScriptUpdateParameter +from ._models_py3 import DeploymentScriptsError +from ._models_py3 import EnvironmentVariable +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorResponse +from ._models_py3 import ManagedServiceIdentity +from ._models_py3 import ScriptConfigurationBase +from ._models_py3 import ScriptLog +from ._models_py3 import ScriptLogsList +from ._models_py3 import ScriptStatus +from ._models_py3 import StorageAccountConfiguration +from ._models_py3 import SystemData +from ._models_py3 import UserAssignedIdentity + +from ._deployment_scripts_client_enums import CleanupOptions +from ._deployment_scripts_client_enums import CreatedByType +from ._deployment_scripts_client_enums import ManagedServiceIdentityType +from ._deployment_scripts_client_enums import ScriptProvisioningState +from ._deployment_scripts_client_enums import ScriptType +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureCliScript", + "AzureCliScriptProperties", + "AzurePowerShellScript", + "AzurePowerShellScriptProperties", + "AzureResourceBase", + "ContainerConfiguration", + "DeploymentScript", + "DeploymentScriptListResult", + "DeploymentScriptPropertiesBase", + "DeploymentScriptUpdateParameter", + "DeploymentScriptsError", + "EnvironmentVariable", + "ErrorAdditionalInfo", + "ErrorResponse", + "ManagedServiceIdentity", + "ScriptConfigurationBase", + "ScriptLog", + "ScriptLogsList", + "ScriptStatus", + "StorageAccountConfiguration", + "SystemData", + "UserAssignedIdentity", + "CleanupOptions", + "CreatedByType", + "ManagedServiceIdentityType", + "ScriptProvisioningState", + "ScriptType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/_deployment_scripts_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/_deployment_scripts_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..41451353e2f9b7ff949d15cd9c6cc76ee704dfef --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/_deployment_scripts_client_enums.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class CleanupOptions(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The clean up preference when the script execution gets in a terminal state. Default setting is + 'Always'. + """ + + ALWAYS = "Always" + ON_SUCCESS = "OnSuccess" + ON_EXPIRATION = "OnExpiration" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + + +class ManagedServiceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the managed identity.""" + + USER_ASSIGNED = "UserAssigned" + + +class ScriptProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """State of the script execution. This only appears in the response.""" + + CREATING = "Creating" + PROVISIONING_RESOURCES = "ProvisioningResources" + RUNNING = "Running" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + CANCELED = "Canceled" + + +class ScriptType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the script.""" + + AZURE_POWER_SHELL = "AzurePowerShell" + AZURE_CLI = "AzureCLI" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..d6bd0533d466f089b9b91144464648d432d8bad0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/_models_py3.py @@ -0,0 +1,1549 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class AzureResourceBase(_serialization.Model): + """Common properties for all Azure resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class DeploymentScript(AzureResourceBase): + """Deployment script object. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureCliScript, AzurePowerShellScript + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + :ivar identity: Optional property. Managed identity to be used for this deployment script. + Currently, only user-assigned MSI is supported. + :vartype identity: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ManagedServiceIdentity + :ivar location: The location of the ACI and the storage account for the deployment script. + Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar kind: Type of the script. Required. Known values are: "AzurePowerShell" and "AzureCLI". + :vartype kind: str or ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptType + :ivar system_data: The system metadata related to this resource. + :vartype system_data: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "kind": {"required": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + _subtype_map = {"kind": {"AzureCLI": "AzureCliScript", "AzurePowerShell": "AzurePowerShellScript"}} + + def __init__( + self, + *, + location: str, + identity: Optional["_models.ManagedServiceIdentity"] = None, + tags: Optional[Dict[str, str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword identity: Optional property. Managed identity to be used for this deployment script. + Currently, only user-assigned MSI is supported. + :paramtype identity: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ManagedServiceIdentity + :keyword location: The location of the ACI and the storage account for the deployment script. + Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.identity = identity + self.location = location + self.tags = tags + self.kind: Optional[str] = None + self.system_data = None + + +class AzureCliScript(DeploymentScript): # pylint: disable=too-many-instance-attributes + """Object model for the Azure CLI script. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + :ivar identity: Optional property. Managed identity to be used for this deployment script. + Currently, only user-assigned MSI is supported. + :vartype identity: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ManagedServiceIdentity + :ivar location: The location of the ACI and the storage account for the deployment script. + Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar kind: Type of the script. Required. Known values are: "AzurePowerShell" and "AzureCLI". + :vartype kind: str or ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptType + :ivar system_data: The system metadata related to this resource. + :vartype system_data: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.SystemData + :ivar container_settings: Container settings. + :vartype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ContainerConfiguration + :ivar storage_account_settings: Storage Account settings. + :vartype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.StorageAccountConfiguration + :ivar cleanup_preference: The clean up preference when the script execution gets in a terminal + state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :vartype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CleanupOptions + :ivar provisioning_state: State of the script execution. This only appears in the response. + Known values are: "Creating", "ProvisioningResources", "Running", "Succeeded", "Failed", and + "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptProvisioningState + :ivar status: Contains the results of script execution. + :vartype status: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptStatus + :ivar outputs: List of script outputs. + :vartype outputs: dict[str, JSON] + :ivar primary_script_uri: Uri for the script. This is the entry point for the external script. + :vartype primary_script_uri: str + :ivar supporting_script_uris: Supporting files for the external script. + :vartype supporting_script_uris: list[str] + :ivar script_content: Script body. + :vartype script_content: str + :ivar arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :vartype arguments: str + :ivar environment_variables: The environment variables to pass over to the script. + :vartype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.EnvironmentVariable] + :ivar force_update_tag: Gets or sets how the deployment script should be forced to execute even + if the script resource has not changed. Can be current time stamp or a GUID. + :vartype force_update_tag: str + :ivar retention_interval: Interval for which the service retains the script resource after it + reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :vartype retention_interval: ~datetime.timedelta + :ivar timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :vartype timeout: ~datetime.timedelta + :ivar az_cli_version: Azure CLI module version to be used. Required. + :vartype az_cli_version: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "kind": {"required": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "status": {"readonly": True}, + "outputs": {"readonly": True}, + "retention_interval": {"required": True}, + "az_cli_version": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "container_settings": {"key": "properties.containerSettings", "type": "ContainerConfiguration"}, + "storage_account_settings": {"key": "properties.storageAccountSettings", "type": "StorageAccountConfiguration"}, + "cleanup_preference": {"key": "properties.cleanupPreference", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "status": {"key": "properties.status", "type": "ScriptStatus"}, + "outputs": {"key": "properties.outputs", "type": "{object}"}, + "primary_script_uri": {"key": "properties.primaryScriptUri", "type": "str"}, + "supporting_script_uris": {"key": "properties.supportingScriptUris", "type": "[str]"}, + "script_content": {"key": "properties.scriptContent", "type": "str"}, + "arguments": {"key": "properties.arguments", "type": "str"}, + "environment_variables": {"key": "properties.environmentVariables", "type": "[EnvironmentVariable]"}, + "force_update_tag": {"key": "properties.forceUpdateTag", "type": "str"}, + "retention_interval": {"key": "properties.retentionInterval", "type": "duration"}, + "timeout": {"key": "properties.timeout", "type": "duration"}, + "az_cli_version": {"key": "properties.azCliVersion", "type": "str"}, + } + + def __init__( + self, + *, + location: str, + retention_interval: datetime.timedelta, + az_cli_version: str, + identity: Optional["_models.ManagedServiceIdentity"] = None, + tags: Optional[Dict[str, str]] = None, + container_settings: Optional["_models.ContainerConfiguration"] = None, + storage_account_settings: Optional["_models.StorageAccountConfiguration"] = None, + cleanup_preference: Union[str, "_models.CleanupOptions"] = "Always", + primary_script_uri: Optional[str] = None, + supporting_script_uris: Optional[List[str]] = None, + script_content: Optional[str] = None, + arguments: Optional[str] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + force_update_tag: Optional[str] = None, + timeout: datetime.timedelta = "P1D", + **kwargs: Any + ) -> None: + """ + :keyword identity: Optional property. Managed identity to be used for this deployment script. + Currently, only user-assigned MSI is supported. + :paramtype identity: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ManagedServiceIdentity + :keyword location: The location of the ACI and the storage account for the deployment script. + Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword container_settings: Container settings. + :paramtype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ContainerConfiguration + :keyword storage_account_settings: Storage Account settings. + :paramtype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.StorageAccountConfiguration + :keyword cleanup_preference: The clean up preference when the script execution gets in a + terminal state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :paramtype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CleanupOptions + :keyword primary_script_uri: Uri for the script. This is the entry point for the external + script. + :paramtype primary_script_uri: str + :keyword supporting_script_uris: Supporting files for the external script. + :paramtype supporting_script_uris: list[str] + :keyword script_content: Script body. + :paramtype script_content: str + :keyword arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :paramtype arguments: str + :keyword environment_variables: The environment variables to pass over to the script. + :paramtype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.EnvironmentVariable] + :keyword force_update_tag: Gets or sets how the deployment script should be forced to execute + even if the script resource has not changed. Can be current time stamp or a GUID. + :paramtype force_update_tag: str + :keyword retention_interval: Interval for which the service retains the script resource after + it reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :paramtype retention_interval: ~datetime.timedelta + :keyword timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :paramtype timeout: ~datetime.timedelta + :keyword az_cli_version: Azure CLI module version to be used. Required. + :paramtype az_cli_version: str + """ + super().__init__(identity=identity, location=location, tags=tags, **kwargs) + self.kind: str = "AzureCLI" + self.container_settings = container_settings + self.storage_account_settings = storage_account_settings + self.cleanup_preference = cleanup_preference + self.provisioning_state = None + self.status = None + self.outputs = None + self.primary_script_uri = primary_script_uri + self.supporting_script_uris = supporting_script_uris + self.script_content = script_content + self.arguments = arguments + self.environment_variables = environment_variables + self.force_update_tag = force_update_tag + self.retention_interval = retention_interval + self.timeout = timeout + self.az_cli_version = az_cli_version + + +class ScriptConfigurationBase(_serialization.Model): + """Common configuration settings for both Azure PowerShell and Azure CLI scripts. + + All required parameters must be populated in order to send to Azure. + + :ivar primary_script_uri: Uri for the script. This is the entry point for the external script. + :vartype primary_script_uri: str + :ivar supporting_script_uris: Supporting files for the external script. + :vartype supporting_script_uris: list[str] + :ivar script_content: Script body. + :vartype script_content: str + :ivar arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :vartype arguments: str + :ivar environment_variables: The environment variables to pass over to the script. + :vartype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.EnvironmentVariable] + :ivar force_update_tag: Gets or sets how the deployment script should be forced to execute even + if the script resource has not changed. Can be current time stamp or a GUID. + :vartype force_update_tag: str + :ivar retention_interval: Interval for which the service retains the script resource after it + reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :vartype retention_interval: ~datetime.timedelta + :ivar timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :vartype timeout: ~datetime.timedelta + """ + + _validation = { + "retention_interval": {"required": True}, + } + + _attribute_map = { + "primary_script_uri": {"key": "primaryScriptUri", "type": "str"}, + "supporting_script_uris": {"key": "supportingScriptUris", "type": "[str]"}, + "script_content": {"key": "scriptContent", "type": "str"}, + "arguments": {"key": "arguments", "type": "str"}, + "environment_variables": {"key": "environmentVariables", "type": "[EnvironmentVariable]"}, + "force_update_tag": {"key": "forceUpdateTag", "type": "str"}, + "retention_interval": {"key": "retentionInterval", "type": "duration"}, + "timeout": {"key": "timeout", "type": "duration"}, + } + + def __init__( + self, + *, + retention_interval: datetime.timedelta, + primary_script_uri: Optional[str] = None, + supporting_script_uris: Optional[List[str]] = None, + script_content: Optional[str] = None, + arguments: Optional[str] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + force_update_tag: Optional[str] = None, + timeout: datetime.timedelta = "P1D", + **kwargs: Any + ) -> None: + """ + :keyword primary_script_uri: Uri for the script. This is the entry point for the external + script. + :paramtype primary_script_uri: str + :keyword supporting_script_uris: Supporting files for the external script. + :paramtype supporting_script_uris: list[str] + :keyword script_content: Script body. + :paramtype script_content: str + :keyword arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :paramtype arguments: str + :keyword environment_variables: The environment variables to pass over to the script. + :paramtype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.EnvironmentVariable] + :keyword force_update_tag: Gets or sets how the deployment script should be forced to execute + even if the script resource has not changed. Can be current time stamp or a GUID. + :paramtype force_update_tag: str + :keyword retention_interval: Interval for which the service retains the script resource after + it reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :paramtype retention_interval: ~datetime.timedelta + :keyword timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :paramtype timeout: ~datetime.timedelta + """ + super().__init__(**kwargs) + self.primary_script_uri = primary_script_uri + self.supporting_script_uris = supporting_script_uris + self.script_content = script_content + self.arguments = arguments + self.environment_variables = environment_variables + self.force_update_tag = force_update_tag + self.retention_interval = retention_interval + self.timeout = timeout + + +class DeploymentScriptPropertiesBase(_serialization.Model): + """Common properties for the deployment script. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar container_settings: Container settings. + :vartype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ContainerConfiguration + :ivar storage_account_settings: Storage Account settings. + :vartype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.StorageAccountConfiguration + :ivar cleanup_preference: The clean up preference when the script execution gets in a terminal + state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :vartype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CleanupOptions + :ivar provisioning_state: State of the script execution. This only appears in the response. + Known values are: "Creating", "ProvisioningResources", "Running", "Succeeded", "Failed", and + "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptProvisioningState + :ivar status: Contains the results of script execution. + :vartype status: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptStatus + :ivar outputs: List of script outputs. + :vartype outputs: dict[str, JSON] + """ + + _validation = { + "provisioning_state": {"readonly": True}, + "status": {"readonly": True}, + "outputs": {"readonly": True}, + } + + _attribute_map = { + "container_settings": {"key": "containerSettings", "type": "ContainerConfiguration"}, + "storage_account_settings": {"key": "storageAccountSettings", "type": "StorageAccountConfiguration"}, + "cleanup_preference": {"key": "cleanupPreference", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "status": {"key": "status", "type": "ScriptStatus"}, + "outputs": {"key": "outputs", "type": "{object}"}, + } + + def __init__( + self, + *, + container_settings: Optional["_models.ContainerConfiguration"] = None, + storage_account_settings: Optional["_models.StorageAccountConfiguration"] = None, + cleanup_preference: Union[str, "_models.CleanupOptions"] = "Always", + **kwargs: Any + ) -> None: + """ + :keyword container_settings: Container settings. + :paramtype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ContainerConfiguration + :keyword storage_account_settings: Storage Account settings. + :paramtype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.StorageAccountConfiguration + :keyword cleanup_preference: The clean up preference when the script execution gets in a + terminal state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :paramtype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CleanupOptions + """ + super().__init__(**kwargs) + self.container_settings = container_settings + self.storage_account_settings = storage_account_settings + self.cleanup_preference = cleanup_preference + self.provisioning_state = None + self.status = None + self.outputs = None + + +class AzureCliScriptProperties( + DeploymentScriptPropertiesBase, ScriptConfigurationBase +): # pylint: disable=too-many-instance-attributes + """Properties of the Azure CLI script object. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar primary_script_uri: Uri for the script. This is the entry point for the external script. + :vartype primary_script_uri: str + :ivar supporting_script_uris: Supporting files for the external script. + :vartype supporting_script_uris: list[str] + :ivar script_content: Script body. + :vartype script_content: str + :ivar arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :vartype arguments: str + :ivar environment_variables: The environment variables to pass over to the script. + :vartype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.EnvironmentVariable] + :ivar force_update_tag: Gets or sets how the deployment script should be forced to execute even + if the script resource has not changed. Can be current time stamp or a GUID. + :vartype force_update_tag: str + :ivar retention_interval: Interval for which the service retains the script resource after it + reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :vartype retention_interval: ~datetime.timedelta + :ivar timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :vartype timeout: ~datetime.timedelta + :ivar container_settings: Container settings. + :vartype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ContainerConfiguration + :ivar storage_account_settings: Storage Account settings. + :vartype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.StorageAccountConfiguration + :ivar cleanup_preference: The clean up preference when the script execution gets in a terminal + state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :vartype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CleanupOptions + :ivar provisioning_state: State of the script execution. This only appears in the response. + Known values are: "Creating", "ProvisioningResources", "Running", "Succeeded", "Failed", and + "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptProvisioningState + :ivar status: Contains the results of script execution. + :vartype status: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptStatus + :ivar outputs: List of script outputs. + :vartype outputs: dict[str, JSON] + :ivar az_cli_version: Azure CLI module version to be used. Required. + :vartype az_cli_version: str + """ + + _validation = { + "retention_interval": {"required": True}, + "provisioning_state": {"readonly": True}, + "status": {"readonly": True}, + "outputs": {"readonly": True}, + "az_cli_version": {"required": True}, + } + + _attribute_map = { + "primary_script_uri": {"key": "primaryScriptUri", "type": "str"}, + "supporting_script_uris": {"key": "supportingScriptUris", "type": "[str]"}, + "script_content": {"key": "scriptContent", "type": "str"}, + "arguments": {"key": "arguments", "type": "str"}, + "environment_variables": {"key": "environmentVariables", "type": "[EnvironmentVariable]"}, + "force_update_tag": {"key": "forceUpdateTag", "type": "str"}, + "retention_interval": {"key": "retentionInterval", "type": "duration"}, + "timeout": {"key": "timeout", "type": "duration"}, + "container_settings": {"key": "containerSettings", "type": "ContainerConfiguration"}, + "storage_account_settings": {"key": "storageAccountSettings", "type": "StorageAccountConfiguration"}, + "cleanup_preference": {"key": "cleanupPreference", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "status": {"key": "status", "type": "ScriptStatus"}, + "outputs": {"key": "outputs", "type": "{object}"}, + "az_cli_version": {"key": "azCliVersion", "type": "str"}, + } + + def __init__( + self, + *, + retention_interval: datetime.timedelta, + az_cli_version: str, + primary_script_uri: Optional[str] = None, + supporting_script_uris: Optional[List[str]] = None, + script_content: Optional[str] = None, + arguments: Optional[str] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + force_update_tag: Optional[str] = None, + timeout: datetime.timedelta = "P1D", + container_settings: Optional["_models.ContainerConfiguration"] = None, + storage_account_settings: Optional["_models.StorageAccountConfiguration"] = None, + cleanup_preference: Union[str, "_models.CleanupOptions"] = "Always", + **kwargs: Any + ) -> None: + """ + :keyword primary_script_uri: Uri for the script. This is the entry point for the external + script. + :paramtype primary_script_uri: str + :keyword supporting_script_uris: Supporting files for the external script. + :paramtype supporting_script_uris: list[str] + :keyword script_content: Script body. + :paramtype script_content: str + :keyword arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :paramtype arguments: str + :keyword environment_variables: The environment variables to pass over to the script. + :paramtype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.EnvironmentVariable] + :keyword force_update_tag: Gets or sets how the deployment script should be forced to execute + even if the script resource has not changed. Can be current time stamp or a GUID. + :paramtype force_update_tag: str + :keyword retention_interval: Interval for which the service retains the script resource after + it reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :paramtype retention_interval: ~datetime.timedelta + :keyword timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :paramtype timeout: ~datetime.timedelta + :keyword container_settings: Container settings. + :paramtype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ContainerConfiguration + :keyword storage_account_settings: Storage Account settings. + :paramtype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.StorageAccountConfiguration + :keyword cleanup_preference: The clean up preference when the script execution gets in a + terminal state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :paramtype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CleanupOptions + :keyword az_cli_version: Azure CLI module version to be used. Required. + :paramtype az_cli_version: str + """ + super().__init__( + container_settings=container_settings, + storage_account_settings=storage_account_settings, + cleanup_preference=cleanup_preference, + primary_script_uri=primary_script_uri, + supporting_script_uris=supporting_script_uris, + script_content=script_content, + arguments=arguments, + environment_variables=environment_variables, + force_update_tag=force_update_tag, + retention_interval=retention_interval, + timeout=timeout, + **kwargs + ) + self.primary_script_uri = primary_script_uri + self.supporting_script_uris = supporting_script_uris + self.script_content = script_content + self.arguments = arguments + self.environment_variables = environment_variables + self.force_update_tag = force_update_tag + self.retention_interval = retention_interval + self.timeout = timeout + self.az_cli_version = az_cli_version + self.container_settings = container_settings + self.storage_account_settings = storage_account_settings + self.cleanup_preference = cleanup_preference + self.provisioning_state = None + self.status = None + self.outputs = None + + +class AzurePowerShellScript(DeploymentScript): # pylint: disable=too-many-instance-attributes + """Object model for the Azure PowerShell script. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + :ivar identity: Optional property. Managed identity to be used for this deployment script. + Currently, only user-assigned MSI is supported. + :vartype identity: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ManagedServiceIdentity + :ivar location: The location of the ACI and the storage account for the deployment script. + Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar kind: Type of the script. Required. Known values are: "AzurePowerShell" and "AzureCLI". + :vartype kind: str or ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptType + :ivar system_data: The system metadata related to this resource. + :vartype system_data: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.SystemData + :ivar container_settings: Container settings. + :vartype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ContainerConfiguration + :ivar storage_account_settings: Storage Account settings. + :vartype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.StorageAccountConfiguration + :ivar cleanup_preference: The clean up preference when the script execution gets in a terminal + state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :vartype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CleanupOptions + :ivar provisioning_state: State of the script execution. This only appears in the response. + Known values are: "Creating", "ProvisioningResources", "Running", "Succeeded", "Failed", and + "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptProvisioningState + :ivar status: Contains the results of script execution. + :vartype status: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptStatus + :ivar outputs: List of script outputs. + :vartype outputs: dict[str, JSON] + :ivar primary_script_uri: Uri for the script. This is the entry point for the external script. + :vartype primary_script_uri: str + :ivar supporting_script_uris: Supporting files for the external script. + :vartype supporting_script_uris: list[str] + :ivar script_content: Script body. + :vartype script_content: str + :ivar arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :vartype arguments: str + :ivar environment_variables: The environment variables to pass over to the script. + :vartype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.EnvironmentVariable] + :ivar force_update_tag: Gets or sets how the deployment script should be forced to execute even + if the script resource has not changed. Can be current time stamp or a GUID. + :vartype force_update_tag: str + :ivar retention_interval: Interval for which the service retains the script resource after it + reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :vartype retention_interval: ~datetime.timedelta + :ivar timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :vartype timeout: ~datetime.timedelta + :ivar az_power_shell_version: Azure PowerShell module version to be used. Required. + :vartype az_power_shell_version: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "kind": {"required": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "status": {"readonly": True}, + "outputs": {"readonly": True}, + "retention_interval": {"required": True}, + "az_power_shell_version": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "container_settings": {"key": "properties.containerSettings", "type": "ContainerConfiguration"}, + "storage_account_settings": {"key": "properties.storageAccountSettings", "type": "StorageAccountConfiguration"}, + "cleanup_preference": {"key": "properties.cleanupPreference", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "status": {"key": "properties.status", "type": "ScriptStatus"}, + "outputs": {"key": "properties.outputs", "type": "{object}"}, + "primary_script_uri": {"key": "properties.primaryScriptUri", "type": "str"}, + "supporting_script_uris": {"key": "properties.supportingScriptUris", "type": "[str]"}, + "script_content": {"key": "properties.scriptContent", "type": "str"}, + "arguments": {"key": "properties.arguments", "type": "str"}, + "environment_variables": {"key": "properties.environmentVariables", "type": "[EnvironmentVariable]"}, + "force_update_tag": {"key": "properties.forceUpdateTag", "type": "str"}, + "retention_interval": {"key": "properties.retentionInterval", "type": "duration"}, + "timeout": {"key": "properties.timeout", "type": "duration"}, + "az_power_shell_version": {"key": "properties.azPowerShellVersion", "type": "str"}, + } + + def __init__( + self, + *, + location: str, + retention_interval: datetime.timedelta, + az_power_shell_version: str, + identity: Optional["_models.ManagedServiceIdentity"] = None, + tags: Optional[Dict[str, str]] = None, + container_settings: Optional["_models.ContainerConfiguration"] = None, + storage_account_settings: Optional["_models.StorageAccountConfiguration"] = None, + cleanup_preference: Union[str, "_models.CleanupOptions"] = "Always", + primary_script_uri: Optional[str] = None, + supporting_script_uris: Optional[List[str]] = None, + script_content: Optional[str] = None, + arguments: Optional[str] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + force_update_tag: Optional[str] = None, + timeout: datetime.timedelta = "P1D", + **kwargs: Any + ) -> None: + """ + :keyword identity: Optional property. Managed identity to be used for this deployment script. + Currently, only user-assigned MSI is supported. + :paramtype identity: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ManagedServiceIdentity + :keyword location: The location of the ACI and the storage account for the deployment script. + Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword container_settings: Container settings. + :paramtype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ContainerConfiguration + :keyword storage_account_settings: Storage Account settings. + :paramtype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.StorageAccountConfiguration + :keyword cleanup_preference: The clean up preference when the script execution gets in a + terminal state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :paramtype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CleanupOptions + :keyword primary_script_uri: Uri for the script. This is the entry point for the external + script. + :paramtype primary_script_uri: str + :keyword supporting_script_uris: Supporting files for the external script. + :paramtype supporting_script_uris: list[str] + :keyword script_content: Script body. + :paramtype script_content: str + :keyword arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :paramtype arguments: str + :keyword environment_variables: The environment variables to pass over to the script. + :paramtype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.EnvironmentVariable] + :keyword force_update_tag: Gets or sets how the deployment script should be forced to execute + even if the script resource has not changed. Can be current time stamp or a GUID. + :paramtype force_update_tag: str + :keyword retention_interval: Interval for which the service retains the script resource after + it reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :paramtype retention_interval: ~datetime.timedelta + :keyword timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :paramtype timeout: ~datetime.timedelta + :keyword az_power_shell_version: Azure PowerShell module version to be used. Required. + :paramtype az_power_shell_version: str + """ + super().__init__(identity=identity, location=location, tags=tags, **kwargs) + self.kind: str = "AzurePowerShell" + self.container_settings = container_settings + self.storage_account_settings = storage_account_settings + self.cleanup_preference = cleanup_preference + self.provisioning_state = None + self.status = None + self.outputs = None + self.primary_script_uri = primary_script_uri + self.supporting_script_uris = supporting_script_uris + self.script_content = script_content + self.arguments = arguments + self.environment_variables = environment_variables + self.force_update_tag = force_update_tag + self.retention_interval = retention_interval + self.timeout = timeout + self.az_power_shell_version = az_power_shell_version + + +class AzurePowerShellScriptProperties( + DeploymentScriptPropertiesBase, ScriptConfigurationBase +): # pylint: disable=too-many-instance-attributes + """Properties of the Azure PowerShell script object. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar primary_script_uri: Uri for the script. This is the entry point for the external script. + :vartype primary_script_uri: str + :ivar supporting_script_uris: Supporting files for the external script. + :vartype supporting_script_uris: list[str] + :ivar script_content: Script body. + :vartype script_content: str + :ivar arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :vartype arguments: str + :ivar environment_variables: The environment variables to pass over to the script. + :vartype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.EnvironmentVariable] + :ivar force_update_tag: Gets or sets how the deployment script should be forced to execute even + if the script resource has not changed. Can be current time stamp or a GUID. + :vartype force_update_tag: str + :ivar retention_interval: Interval for which the service retains the script resource after it + reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :vartype retention_interval: ~datetime.timedelta + :ivar timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :vartype timeout: ~datetime.timedelta + :ivar container_settings: Container settings. + :vartype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ContainerConfiguration + :ivar storage_account_settings: Storage Account settings. + :vartype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.StorageAccountConfiguration + :ivar cleanup_preference: The clean up preference when the script execution gets in a terminal + state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :vartype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CleanupOptions + :ivar provisioning_state: State of the script execution. This only appears in the response. + Known values are: "Creating", "ProvisioningResources", "Running", "Succeeded", "Failed", and + "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptProvisioningState + :ivar status: Contains the results of script execution. + :vartype status: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptStatus + :ivar outputs: List of script outputs. + :vartype outputs: dict[str, JSON] + :ivar az_power_shell_version: Azure PowerShell module version to be used. Required. + :vartype az_power_shell_version: str + """ + + _validation = { + "retention_interval": {"required": True}, + "provisioning_state": {"readonly": True}, + "status": {"readonly": True}, + "outputs": {"readonly": True}, + "az_power_shell_version": {"required": True}, + } + + _attribute_map = { + "primary_script_uri": {"key": "primaryScriptUri", "type": "str"}, + "supporting_script_uris": {"key": "supportingScriptUris", "type": "[str]"}, + "script_content": {"key": "scriptContent", "type": "str"}, + "arguments": {"key": "arguments", "type": "str"}, + "environment_variables": {"key": "environmentVariables", "type": "[EnvironmentVariable]"}, + "force_update_tag": {"key": "forceUpdateTag", "type": "str"}, + "retention_interval": {"key": "retentionInterval", "type": "duration"}, + "timeout": {"key": "timeout", "type": "duration"}, + "container_settings": {"key": "containerSettings", "type": "ContainerConfiguration"}, + "storage_account_settings": {"key": "storageAccountSettings", "type": "StorageAccountConfiguration"}, + "cleanup_preference": {"key": "cleanupPreference", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "status": {"key": "status", "type": "ScriptStatus"}, + "outputs": {"key": "outputs", "type": "{object}"}, + "az_power_shell_version": {"key": "azPowerShellVersion", "type": "str"}, + } + + def __init__( + self, + *, + retention_interval: datetime.timedelta, + az_power_shell_version: str, + primary_script_uri: Optional[str] = None, + supporting_script_uris: Optional[List[str]] = None, + script_content: Optional[str] = None, + arguments: Optional[str] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + force_update_tag: Optional[str] = None, + timeout: datetime.timedelta = "P1D", + container_settings: Optional["_models.ContainerConfiguration"] = None, + storage_account_settings: Optional["_models.StorageAccountConfiguration"] = None, + cleanup_preference: Union[str, "_models.CleanupOptions"] = "Always", + **kwargs: Any + ) -> None: + """ + :keyword primary_script_uri: Uri for the script. This is the entry point for the external + script. + :paramtype primary_script_uri: str + :keyword supporting_script_uris: Supporting files for the external script. + :paramtype supporting_script_uris: list[str] + :keyword script_content: Script body. + :paramtype script_content: str + :keyword arguments: Command line arguments to pass to the script. Arguments are separated by + spaces. ex: -Name blue* -Location 'West US 2'. + :paramtype arguments: str + :keyword environment_variables: The environment variables to pass over to the script. + :paramtype environment_variables: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.EnvironmentVariable] + :keyword force_update_tag: Gets or sets how the deployment script should be forced to execute + even if the script resource has not changed. Can be current time stamp or a GUID. + :paramtype force_update_tag: str + :keyword retention_interval: Interval for which the service retains the script resource after + it reaches a terminal state. Resource will be deleted when this duration expires. Duration is + based on ISO 8601 pattern (for example P1D means one day). Required. + :paramtype retention_interval: ~datetime.timedelta + :keyword timeout: Maximum allowed script execution time specified in ISO 8601 format. Default + value is P1D. + :paramtype timeout: ~datetime.timedelta + :keyword container_settings: Container settings. + :paramtype container_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ContainerConfiguration + :keyword storage_account_settings: Storage Account settings. + :paramtype storage_account_settings: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.StorageAccountConfiguration + :keyword cleanup_preference: The clean up preference when the script execution gets in a + terminal state. Default setting is 'Always'. Known values are: "Always", "OnSuccess", and + "OnExpiration". + :paramtype cleanup_preference: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CleanupOptions + :keyword az_power_shell_version: Azure PowerShell module version to be used. Required. + :paramtype az_power_shell_version: str + """ + super().__init__( + container_settings=container_settings, + storage_account_settings=storage_account_settings, + cleanup_preference=cleanup_preference, + primary_script_uri=primary_script_uri, + supporting_script_uris=supporting_script_uris, + script_content=script_content, + arguments=arguments, + environment_variables=environment_variables, + force_update_tag=force_update_tag, + retention_interval=retention_interval, + timeout=timeout, + **kwargs + ) + self.primary_script_uri = primary_script_uri + self.supporting_script_uris = supporting_script_uris + self.script_content = script_content + self.arguments = arguments + self.environment_variables = environment_variables + self.force_update_tag = force_update_tag + self.retention_interval = retention_interval + self.timeout = timeout + self.az_power_shell_version = az_power_shell_version + self.container_settings = container_settings + self.storage_account_settings = storage_account_settings + self.cleanup_preference = cleanup_preference + self.provisioning_state = None + self.status = None + self.outputs = None + + +class ContainerConfiguration(_serialization.Model): + """Settings to customize ACI container instance. + + :ivar container_group_name: Container group name, if not specified then the name will get + auto-generated. Not specifying a 'containerGroupName' indicates the system to generate a unique + name which might end up flagging an Azure Policy as non-compliant. Use 'containerGroupName' + when you have an Azure Policy that expects a specific naming convention or when you want to + fully control the name. 'containerGroupName' property must be between 1 and 63 characters long, + must contain only lowercase letters, numbers, and dashes and it cannot start or end with a dash + and consecutive dashes are not allowed. To specify a 'containerGroupName', add the following + object to properties: { "containerSettings": { "containerGroupName": "contoso-container" } }. + If you do not want to specify a 'containerGroupName' then do not add 'containerSettings' + property. + :vartype container_group_name: str + """ + + _validation = { + "container_group_name": {"max_length": 63, "min_length": 1}, + } + + _attribute_map = { + "container_group_name": {"key": "containerGroupName", "type": "str"}, + } + + def __init__(self, *, container_group_name: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword container_group_name: Container group name, if not specified then the name will get + auto-generated. Not specifying a 'containerGroupName' indicates the system to generate a unique + name which might end up flagging an Azure Policy as non-compliant. Use 'containerGroupName' + when you have an Azure Policy that expects a specific naming convention or when you want to + fully control the name. 'containerGroupName' property must be between 1 and 63 characters long, + must contain only lowercase letters, numbers, and dashes and it cannot start or end with a dash + and consecutive dashes are not allowed. To specify a 'containerGroupName', add the following + object to properties: { "containerSettings": { "containerGroupName": "contoso-container" } }. + If you do not want to specify a 'containerGroupName' then do not add 'containerSettings' + property. + :paramtype container_group_name: str + """ + super().__init__(**kwargs) + self.container_group_name = container_group_name + + +class DeploymentScriptListResult(_serialization.Model): + """List of deployment scripts. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: An array of deployment scripts. + :vartype value: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _validation = { + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[DeploymentScript]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[List["_models.DeploymentScript"]] = None, **kwargs: Any) -> None: + """ + :keyword value: An array of deployment scripts. + :paramtype value: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + """ + super().__init__(**kwargs) + self.value = value + self.next_link = None + + +class DeploymentScriptsError(_serialization.Model): + """Deployment scripts error response. + + :ivar error: Common error response for all Azure Resource Manager APIs to return error details + for failed operations. (This also follows the OData error response format.). + :vartype error: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ErrorResponse + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorResponse"}, + } + + def __init__(self, *, error: Optional["_models.ErrorResponse"] = None, **kwargs: Any) -> None: + """ + :keyword error: Common error response for all Azure Resource Manager APIs to return error + details for failed operations. (This also follows the OData error response format.). + :paramtype error: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ErrorResponse + """ + super().__init__(**kwargs) + self.error = error + + +class DeploymentScriptUpdateParameter(AzureResourceBase): + """Deployment script parameters to be updated. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + :ivar tags: Resource tags to be updated. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Resource tags to be updated. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.tags = tags + + +class EnvironmentVariable(_serialization.Model): + """The environment variable to pass to the script in the container instance. + + All required parameters must be populated in order to send to Azure. + + :ivar name: The name of the environment variable. Required. + :vartype name: str + :ivar value: The value of the environment variable. + :vartype value: str + :ivar secure_value: The value of the secure environment variable. + :vartype secure_value: str + """ + + _validation = { + "name": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, + "secure_value": {"key": "secureValue", "type": "str"}, + } + + def __init__( + self, *, name: str, value: Optional[str] = None, secure_value: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword name: The name of the environment variable. Required. + :paramtype name: str + :keyword value: The value of the environment variable. + :paramtype value: str + :keyword secure_value: The value of the secure environment variable. + :paramtype secure_value: str + """ + super().__init__(**kwargs) + self.name = name + self.value = value + self.secure_value = secure_value + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorResponse]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ManagedServiceIdentity(_serialization.Model): + """Managed identity generic object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: Type of the managed identity. "UserAssigned" + :vartype type: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ManagedServiceIdentityType + :ivar tenant_id: ID of the Azure Active Directory. + :vartype tenant_id: str + :ivar user_assigned_identities: The list of user-assigned managed identities associated with + the resource. Key is the Azure resource Id of the managed identity. + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.UserAssignedIdentity] + """ + + _validation = { + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentity}"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.ManagedServiceIdentityType"]] = None, + user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentity"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: Type of the managed identity. "UserAssigned" + :paramtype type: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ManagedServiceIdentityType + :keyword user_assigned_identities: The list of user-assigned managed identities associated with + the resource. Key is the Azure resource Id of the managed identity. + :paramtype user_assigned_identities: dict[str, + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.UserAssignedIdentity] + """ + super().__init__(**kwargs) + self.type = type + self.tenant_id = None + self.user_assigned_identities = user_assigned_identities + + +class ScriptLog(AzureResourceBase): + """Script execution log object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: String Id used to locate any resource on Azure. + :vartype id: str + :ivar name: Name of this resource. + :vartype name: str + :ivar type: Type of this resource. + :vartype type: str + :ivar log: Script execution logs in text format. + :vartype log: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "log": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "log": {"key": "properties.log", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.log = None + + +class ScriptLogsList(_serialization.Model): + """Deployment script execution logs. + + :ivar value: Deployment scripts logs. + :vartype value: list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptLog] + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ScriptLog]"}, + } + + def __init__(self, *, value: Optional[List["_models.ScriptLog"]] = None, **kwargs: Any) -> None: + """ + :keyword value: Deployment scripts logs. + :paramtype value: list[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptLog] + """ + super().__init__(**kwargs) + self.value = value + + +class ScriptStatus(_serialization.Model): + """Generic object modeling results of script execution. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar container_instance_id: ACI resource Id. + :vartype container_instance_id: str + :ivar storage_account_id: Storage account resource Id. + :vartype storage_account_id: str + :ivar start_time: Start time of the script execution. + :vartype start_time: ~datetime.datetime + :ivar end_time: End time of the script execution. + :vartype end_time: ~datetime.datetime + :ivar expiration_time: Time the deployment script resource will expire. + :vartype expiration_time: ~datetime.datetime + :ivar error: Error that is relayed from the script execution. + :vartype error: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ErrorResponse + """ + + _validation = { + "container_instance_id": {"readonly": True}, + "storage_account_id": {"readonly": True}, + "start_time": {"readonly": True}, + "end_time": {"readonly": True}, + "expiration_time": {"readonly": True}, + } + + _attribute_map = { + "container_instance_id": {"key": "containerInstanceId", "type": "str"}, + "storage_account_id": {"key": "storageAccountId", "type": "str"}, + "start_time": {"key": "startTime", "type": "iso-8601"}, + "end_time": {"key": "endTime", "type": "iso-8601"}, + "expiration_time": {"key": "expirationTime", "type": "iso-8601"}, + "error": {"key": "error", "type": "ErrorResponse"}, + } + + def __init__(self, *, error: Optional["_models.ErrorResponse"] = None, **kwargs: Any) -> None: + """ + :keyword error: Error that is relayed from the script execution. + :paramtype error: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ErrorResponse + """ + super().__init__(**kwargs) + self.container_instance_id = None + self.storage_account_id = None + self.start_time = None + self.end_time = None + self.expiration_time = None + self.error = error + + +class StorageAccountConfiguration(_serialization.Model): + """Settings to use an existing storage account. Valid storage account kinds are: Storage, + StorageV2 and FileStorage. + + :ivar storage_account_name: The storage account name. + :vartype storage_account_name: str + :ivar storage_account_key: The storage account access key. + :vartype storage_account_key: str + """ + + _attribute_map = { + "storage_account_name": {"key": "storageAccountName", "type": "str"}, + "storage_account_key": {"key": "storageAccountKey", "type": "str"}, + } + + def __init__( + self, *, storage_account_name: Optional[str] = None, storage_account_key: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword storage_account_name: The storage account name. + :paramtype storage_account_name: str + :keyword storage_account_key: The storage account access key. + :paramtype storage_account_key: str + """ + super().__init__(**kwargs) + self.storage_account_name = storage_account_name + self.storage_account_key = storage_account_key + + +class SystemData(_serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + } + + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword created_by: The identity that created the resource. + :paramtype created_by: str + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :paramtype created_by_type: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CreatedByType + :keyword created_at: The timestamp of resource creation (UTC). + :paramtype created_at: ~datetime.datetime + :keyword last_modified_by: The identity that last modified the resource. + :paramtype last_modified_by: str + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". + :paramtype last_modified_by_type: str or + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.CreatedByType + :keyword last_modified_at: The timestamp of resource last modification (UTC). + :paramtype last_modified_at: ~datetime.datetime + """ + super().__init__(**kwargs) + self.created_by = created_by + self.created_by_type = created_by_type + self.created_at = created_at + self.last_modified_by = last_modified_by + self.last_modified_by_type = last_modified_by_type + self.last_modified_at = last_modified_at + + +class UserAssignedIdentity(_serialization.Model): + """User-assigned managed identity. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: Azure Active Directory principal ID associated with this identity. + :vartype principal_id: str + :ivar client_id: Client App Id associated with this identity. + :vartype client_id: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.principal_id = None + self.client_id = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3629550dcb98f22eccc765c9aa9e479a046b860e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import DeploymentScriptsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DeploymentScriptsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..6f5262daa7307e3c06444b6700bb216a016c4bcf --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/operations/_operations.py @@ -0,0 +1,1136 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_deployment_scripts_create_request( + resource_group_name: str, script_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_update_request( + resource_group_name: str, script_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_get_request( + resource_group_name: str, script_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_delete_request( + resource_group_name: str, script_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/deploymentScripts") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_get_logs_request( + resource_group_name: str, script_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_get_logs_default_request( + resource_group_name: str, script_name: str, subscription_id: str, *, tail: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "scriptName": _SERIALIZER.url("script_name", script_name, "str", max_length=90, min_length=1), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tail is not None: + _params["tail"] = _SERIALIZER.query("tail", tail, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_deployment_scripts_list_by_resource_group_request( + resource_group_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DeploymentScriptsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.deploymentscripts.v2020_10_01.DeploymentScriptsClient`'s + :attr:`deployment_scripts` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def _create_initial( + self, + resource_group_name: str, + script_name: str, + deployment_script: Union[_models.DeploymentScript, IO], + **kwargs: Any + ) -> _models.DeploymentScript: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(deployment_script, (IO, bytes)): + _content = deployment_script + else: + _json = self._serialize.body(deployment_script, "DeploymentScript") + + request = build_deployment_scripts_create_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @overload + def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: _models.DeploymentScript, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Required. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Required. + :type deployment_script: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create( + self, + resource_group_name: str, + script_name: str, + deployment_script: Union[_models.DeploymentScript, IO], + **kwargs: Any + ) -> LROPoller[_models.DeploymentScript]: + """Creates a deployment script. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script supplied to the operation. Is either a + DeploymentScript type or a IO type. Required. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DeploymentScript or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + script_name=script_name, + deployment_script=deployment_script, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DeploymentScript", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @overload + def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[_models.DeploymentScriptUpdateParameter] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Default value + is None. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScriptUpdateParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[IO] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Default value + is None. + :type deployment_script: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + resource_group_name: str, + script_name: str, + deployment_script: Optional[Union[_models.DeploymentScriptUpdateParameter, IO]] = None, + **kwargs: Any + ) -> _models.DeploymentScript: + """Updates deployment script tags with specified values. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param deployment_script: Deployment script resource with the tags to be updated. Is either a + DeploymentScriptUpdateParameter type or a IO type. Default value is None. + :type deployment_script: + ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScriptUpdateParameter or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(deployment_script, (IO, bytes)): + _content = deployment_script + else: + if deployment_script is not None: + _json = self._serialize.body(deployment_script, "DeploymentScriptUpdateParameter") + else: + _json = None + + request = build_deployment_scripts_update_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace + def get(self, resource_group_name: str, script_name: str, **kwargs: Any) -> _models.DeploymentScript: + """Gets a deployment script with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DeploymentScript or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[_models.DeploymentScript] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DeploymentScript", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, script_name: str, **kwargs: Any + ) -> None: + """Deletes a deployment script. When operation completes, status code 200 returned without + content. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_deployment_scripts_delete_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}" + } + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DeploymentScript"]: + """Lists all deployment scripts for a given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DeploymentScript or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[_models.DeploymentScriptListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_deployment_scripts_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DeploymentScriptListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_subscription.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/deploymentScripts" + } + + @distributed_trace + def get_logs(self, resource_group_name: str, script_name: str, **kwargs: Any) -> _models.ScriptLogsList: + """Gets deployment script logs for a given deployment script name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScriptLogsList or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptLogsList + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[_models.ScriptLogsList] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_logs_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_logs.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScriptLogsList", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_logs.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs" + } + + @distributed_trace + def get_logs_default( + self, resource_group_name: str, script_name: str, tail: Optional[int] = None, **kwargs: Any + ) -> _models.ScriptLog: + """Gets deployment script logs for a given deployment script name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param script_name: Name of the deployment script. Required. + :type script_name: str + :param tail: The number of lines to show from the tail of the deployment script log. Valid + value is a positive number up to 1000. If 'tail' is not provided, all available logs are shown + up to container instance log capacity of 4mb. Default value is None. + :type tail: int + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScriptLog or the result of cls(response) + :rtype: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ScriptLog + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[_models.ScriptLog] = kwargs.pop("cls", None) + + request = build_deployment_scripts_get_logs_default_request( + resource_group_name=resource_group_name, + script_name=script_name, + subscription_id=self._config.subscription_id, + tail=tail, + api_version=api_version, + template_url=self.get_logs_default.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScriptLog", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_logs_default.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs/default" + } + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.DeploymentScript"]: + """Lists deployments scripts. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DeploymentScript or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.DeploymentScript] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + cls: ClsType[_models.DeploymentScriptListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_deployment_scripts_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DeploymentScriptListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.DeploymentScriptsError, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/v2020_10_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..559619025efeb3aa8ef35f64290d37c698fd5b68 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._feature_client import FeatureClient +__all__ = ['FeatureClient'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..2cd5598cb0027ab5f4a0020a05633292d5f74bc8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class FeatureClientConfiguration(Configuration): + """Configuration for FeatureClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. Required. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(FeatureClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'azure-mgmt-resource/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/_feature_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/_feature_client.py new file mode 100644 index 0000000000000000000000000000000000000000..0a572949c8fef0b771e2f351406db14ae7565b80 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/_feature_client.py @@ -0,0 +1,137 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.mgmt.core import AsyncARMPipelineClient +from azure.profiles import KnownProfiles, ProfileDefinition +from azure.profiles.multiapiclient import MultiApiClientMixin + +from .._serialization import Deserializer, Serializer +from ._configuration import FeatureClientConfiguration +from ._operations_mixin import FeatureClientOperationsMixin + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class _SDKClient(object): + def __init__(self, *args, **kwargs): + """This is a fake class to support current implemetation of MultiApiClientMixin." + Will be removed in final version of multiapi azure-core based client + """ + pass + +class FeatureClient(FeatureClientOperationsMixin, MultiApiClientMixin, _SDKClient): + """Azure Feature Exposure Control (AFEC) provides a mechanism for the resource providers to control feature exposure to users. Resource providers typically use this mechanism to provide public/private preview for new features prior to making them generally available. Users need to explicitly register for AFEC features to get access to such functionality. + + This ready contains multiple API versions, to help you deal with all of the Azure clouds + (Azure Stack, Azure Government, Azure China, etc.). + By default, it uses the latest API version available on public Azure. + For production, you should stick to a particular api-version and/or profile. + The profile sets a mapping between an operation group and its API version. + The api-version parameter sets the default API version if the operation + group is not described in the profile. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. Required. + :type subscription_id: str + :param api_version: API version to use if no profile is provided, or if missing in profile. + :type api_version: str + :param base_url: Service URL + :type base_url: str + :param profile: A profile definition, from KnownProfiles to dict. + :type profile: azure.profiles.KnownProfiles + """ + + DEFAULT_API_VERSION = '2021-07-01' + _PROFILE_TAG = "azure.mgmt.resource.features.FeatureClient" + LATEST_PROFILE = ProfileDefinition({ + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + }}, + _PROFILE_TAG + " latest" + ) + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + api_version: Optional[str] = None, + base_url: str = "https://management.azure.com", + profile: KnownProfiles = KnownProfiles.default, + **kwargs: Any + ) -> None: + self._config = FeatureClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + super(FeatureClient, self).__init__( + api_version=api_version, + profile=profile + ) + + @classmethod + def _models_dict(cls, api_version): + return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} + + @classmethod + def models(cls, api_version=DEFAULT_API_VERSION): + """Module depends on the API version: + + * 2015-12-01: :mod:`v2015_12_01.models` + * 2021-07-01: :mod:`v2021_07_01.models` + """ + if api_version == '2015-12-01': + from ..v2015_12_01 import models + return models + elif api_version == '2021-07-01': + from ..v2021_07_01 import models + return models + raise ValueError("API version {} is not available".format(api_version)) + + @property + def features(self): + """Instance depends on the API version: + + * 2015-12-01: :class:`FeaturesOperations` + * 2021-07-01: :class:`FeaturesOperations` + """ + api_version = self._get_api_version('features') + if api_version == '2015-12-01': + from ..v2015_12_01.aio.operations import FeaturesOperations as OperationClass + elif api_version == '2021-07-01': + from ..v2021_07_01.aio.operations import FeaturesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'features'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def subscription_feature_registrations(self): + """Instance depends on the API version: + + * 2021-07-01: :class:`SubscriptionFeatureRegistrationsOperations` + """ + api_version = self._get_api_version('subscription_feature_registrations') + if api_version == '2021-07-01': + from ..v2021_07_01.aio.operations import SubscriptionFeatureRegistrationsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'subscription_feature_registrations'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + async def close(self): + await self._client.close() + async def __aenter__(self): + await self._client.__aenter__() + return self + async def __aexit__(self, *exc_details): + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/_operations_mixin.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/_operations_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..644b5d633af619037854a61388fae2feb4b3af48 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/aio/_operations_mixin.py @@ -0,0 +1,47 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from .._serialization import Serializer, Deserializer +from typing import Any, AsyncIterable + +from azure.core.async_paging import AsyncItemPaged + +from .. import models as _models + + +class FeatureClientOperationsMixin(object): + + def list_operations( + self, + **kwargs: Any + ) -> AsyncIterable["_models.Operation"]: + """Lists all of the available Microsoft.Features REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.v2021_07_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + api_version = self._get_api_version('list_operations') + if api_version == '2015-12-01': + from ..v2015_12_01.aio.operations import FeatureClientOperationsMixin as OperationClass + elif api_version == '2021-07-01': + from ..v2021_07_01.aio.operations import FeatureClientOperationsMixin as OperationClass + else: + raise ValueError("API version {} does not have operation 'list_operations'".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._config.api_version = api_version + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._serialize.client_side_validation = False + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return mixin_instance.list_operations(**kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..db62bac61b6e5782500110478df595bed4f26925 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._feature_client import FeatureClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeatureClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..2cb0d093df9b072a688b9f3edb4c782ccd6b4ee4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class FeatureClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for FeatureClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-12-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(FeatureClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", "2015-12-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_feature_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_feature_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b66ac6d5fadf83c48b60c2335d57bba2ba2d7ac2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_feature_client.py @@ -0,0 +1,90 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import FeatureClientConfiguration +from .operations import FeatureClientOperationsMixin, FeaturesOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class FeatureClient(FeatureClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """Azure Feature Exposure Control (AFEC) provides a mechanism for the resource providers to + control feature exposure to users. Resource providers typically use this mechanism to provide + public/private preview for new features prior to making them generally available. Users need to + explicitly register for AFEC features to get access to such functionality. + + :ivar features: FeaturesOperations operations + :vartype features: azure.mgmt.resource.features.v2015_12_01.operations.FeaturesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2015-12-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = FeatureClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "FeatureClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7da72b39ac776d1b0c2660b3c698b6eb2635c1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_vendor.py @@ -0,0 +1,48 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import List, TYPE_CHECKING, cast + +from azure.core.pipeline.transport import HttpRequest + +from ._configuration import FeatureClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core import PipelineClient + + from .._serialization import Deserializer, Serializer + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) + + +class FeatureClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "PipelineClient" + _config: FeatureClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..38ced0793f4166879d6ef8932a3e97f0cf1f3239 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "23.0.1" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43af45c2778fdf0e798a37814a099d9a1e1012e3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._feature_client import FeatureClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeatureClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..8efc01ac871009a52e4ea1510ce5e309943f47fb --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class FeatureClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for FeatureClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-12-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(FeatureClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", "2015-12-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_feature_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_feature_client.py new file mode 100644 index 0000000000000000000000000000000000000000..baa2b0e9f8421180d6aa23ace2accec418dc081a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_feature_client.py @@ -0,0 +1,90 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import FeatureClientConfiguration +from .operations import FeatureClientOperationsMixin, FeaturesOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class FeatureClient(FeatureClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """Azure Feature Exposure Control (AFEC) provides a mechanism for the resource providers to + control feature exposure to users. Resource providers typically use this mechanism to provide + public/private preview for new features prior to making them generally available. Users need to + explicitly register for AFEC features to get access to such functionality. + + :ivar features: FeaturesOperations operations + :vartype features: azure.mgmt.resource.features.v2015_12_01.aio.operations.FeaturesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2015-12-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = FeatureClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "FeatureClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..c93c7557db14f7faefeb7948b8db3f8b175b023f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/_vendor.py @@ -0,0 +1,28 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import TYPE_CHECKING + +from azure.core.pipeline.transport import HttpRequest + +from ._configuration import FeatureClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core import AsyncPipelineClient + + from ..._serialization import Deserializer, Serializer + + +class FeatureClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "AsyncPipelineClient" + _config: FeatureClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f566b08e6dc8d10494caaf6ef7d0ad5ca2cab20e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import FeatureClientOperationsMixin +from ._operations import FeaturesOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeatureClientOperationsMixin", + "FeaturesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..c84786575fe2d5ce90738afda19e07aea78623a4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/operations/_operations.py @@ -0,0 +1,505 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_feature_list_operations_request, + build_features_get_request, + build_features_list_all_request, + build_features_list_request, + build_features_register_request, + build_features_unregister_request, +) +from .._vendor import FeatureClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class FeatureClientOperationsMixin(FeatureClientMixinABC): + @distributed_trace + def list_operations(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + """Lists all of the available Microsoft.Features REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.v2015_12_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_feature_list_operations_request( + api_version=api_version, + template_url=self.list_operations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_operations.metadata = {"url": "/providers/Microsoft.Features/operations"} + + +class FeaturesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.features.v2015_12_01.aio.FeatureClient`'s + :attr:`features` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_all(self, **kwargs: Any) -> AsyncIterable["_models.FeatureResult"]: + """Gets all the preview features that are available through AFEC for the subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_features_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_all.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_all.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/features"} + + @distributed_trace + def list(self, resource_provider_namespace: str, **kwargs: Any) -> AsyncIterable["_models.FeatureResult"]: + """Gets all the preview features in a provider namespace that are available through AFEC for the + subscription. + + :param resource_provider_namespace: The namespace of the resource provider for getting + features. Required. + :type resource_provider_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_features_list_request( + resource_provider_namespace=resource_provider_namespace, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features" + } + + @distributed_trace_async + async def get(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Gets the preview feature with the specified name. + + :param resource_provider_namespace: The resource provider namespace for the feature. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to get. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_get_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}" + } + + @distributed_trace_async + async def register( + self, resource_provider_namespace: str, feature_name: str, **kwargs: Any + ) -> _models.FeatureResult: + """Registers the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to register. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_register_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.register.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + register.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register" + } + + @distributed_trace_async + async def unregister( + self, resource_provider_namespace: str, feature_name: str, **kwargs: Any + ) -> _models.FeatureResult: + """Unregisters the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to unregister. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_unregister_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.unregister.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + unregister.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba6ccc60871a6db45605fb4d750ff74dd8df4f4a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/models/__init__.py @@ -0,0 +1,28 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import FeatureOperationsListResult +from ._models_py3 import FeatureProperties +from ._models_py3 import FeatureResult +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeatureOperationsListResult", + "FeatureProperties", + "FeatureResult", + "Operation", + "OperationDisplay", + "OperationListResult", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..e36a8c371c3c398e16995e5fc461b3812f9fc639 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/models/_models_py3.py @@ -0,0 +1,206 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, List, Optional, TYPE_CHECKING + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class FeatureOperationsListResult(_serialization.Model): + """List of previewed features. + + :ivar value: The array of features. + :vartype value: list[~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[FeatureResult]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.FeatureResult"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: The array of features. + :paramtype value: list[~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class FeatureProperties(_serialization.Model): + """Information about feature. + + :ivar state: The registration state of the feature for the subscription. + :vartype state: str + """ + + _attribute_map = { + "state": {"key": "state", "type": "str"}, + } + + def __init__(self, *, state: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword state: The registration state of the feature for the subscription. + :paramtype state: str + """ + super().__init__(**kwargs) + self.state = state + + +class FeatureResult(_serialization.Model): + """Previewed feature information. + + :ivar name: The name of the feature. + :vartype name: str + :ivar properties: Properties of the previewed feature. + :vartype properties: ~azure.mgmt.resource.features.v2015_12_01.models.FeatureProperties + :ivar id: The resource ID of the feature. + :vartype id: str + :ivar type: The resource type of the feature. + :vartype type: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "FeatureProperties"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + properties: Optional["_models.FeatureProperties"] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + type: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of the feature. + :paramtype name: str + :keyword properties: Properties of the previewed feature. + :paramtype properties: ~azure.mgmt.resource.features.v2015_12_01.models.FeatureProperties + :keyword id: The resource ID of the feature. + :paramtype id: str + :keyword type: The resource type of the feature. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.properties = properties + self.id = id + self.type = type + + +class Operation(_serialization.Model): + """Microsoft.Features operation. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.resource.features.v2015_12_01.models.OperationDisplay + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + } + + def __init__( + self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any + ) -> None: + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: The object that represents the operation. + :paramtype display: ~azure.mgmt.resource.features.v2015_12_01.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = name + self.display = display + + +class OperationDisplay(_serialization.Model): + """The object that represents the operation. + + :ivar provider: Service provider: Microsoft.Features. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + """ + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Service provider: Microsoft.Features. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. + :paramtype resource: str + :keyword operation: Operation type: Read, write, delete, etc. + :paramtype operation: str + """ + super().__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + + +class OperationListResult(_serialization.Model): + """Result of the request to list Microsoft.Features operations. It contains a list of operations + and a URL link to get the next set of results. + + :ivar value: List of Microsoft.Features operations. + :vartype value: list[~azure.mgmt.resource.features.v2015_12_01.models.Operation] + :ivar next_link: URL to get the next set of operation list results if there are any. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: List of Microsoft.Features operations. + :paramtype value: list[~azure.mgmt.resource.features.v2015_12_01.models.Operation] + :keyword next_link: URL to get the next set of operation list results if there are any. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f566b08e6dc8d10494caaf6ef7d0ad5ca2cab20e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import FeatureClientOperationsMixin +from ._operations import FeaturesOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeatureClientOperationsMixin", + "FeaturesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..43d868ac5e2a5db118a4da44fceb08fcfc5a8c8d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/operations/_operations.py @@ -0,0 +1,659 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import FeatureClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_feature_list_operations_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Features/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_list_all_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Features/features") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_list_request(resource_provider_namespace: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_get_request( + resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_register_request( + resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_unregister_request( + resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class FeatureClientOperationsMixin(FeatureClientMixinABC): + @distributed_trace + def list_operations(self, **kwargs: Any) -> Iterable["_models.Operation"]: + """Lists all of the available Microsoft.Features REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.v2015_12_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_feature_list_operations_request( + api_version=api_version, + template_url=self.list_operations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_operations.metadata = {"url": "/providers/Microsoft.Features/operations"} + + +class FeaturesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.features.v2015_12_01.FeatureClient`'s + :attr:`features` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_all(self, **kwargs: Any) -> Iterable["_models.FeatureResult"]: + """Gets all the preview features that are available through AFEC for the subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_features_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_all.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_all.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/features"} + + @distributed_trace + def list(self, resource_provider_namespace: str, **kwargs: Any) -> Iterable["_models.FeatureResult"]: + """Gets all the preview features in a provider namespace that are available through AFEC for the + subscription. + + :param resource_provider_namespace: The namespace of the resource provider for getting + features. Required. + :type resource_provider_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_features_list_request( + resource_provider_namespace=resource_provider_namespace, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features" + } + + @distributed_trace + def get(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Gets the preview feature with the specified name. + + :param resource_provider_namespace: The resource provider namespace for the feature. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to get. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_get_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}" + } + + @distributed_trace + def register(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Registers the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to register. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_register_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.register.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + register.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register" + } + + @distributed_trace + def unregister(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Unregisters the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to unregister. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2015_12_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-12-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_unregister_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.unregister.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + unregister.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2015_12_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..db62bac61b6e5782500110478df595bed4f26925 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._feature_client import FeatureClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeatureClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..941f0066a82cca061faa62b8dec9d6bf8d01f5ef --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class FeatureClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for FeatureClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(FeatureClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", "2021-07-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_feature_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_feature_client.py new file mode 100644 index 0000000000000000000000000000000000000000..7bf28cbdd5d900cfb066d3842c99a3a2d5a6af51 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_feature_client.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import FeatureClientConfiguration +from .operations import FeatureClientOperationsMixin, FeaturesOperations, SubscriptionFeatureRegistrationsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class FeatureClient(FeatureClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """Azure Feature Exposure Control (AFEC) provides a mechanism for the resource providers to + control feature exposure to users. Resource providers typically use this mechanism to provide + public/private preview for new features prior to making them generally available. Users need to + explicitly register for AFEC features to get access to such functionality. + + :ivar features: FeaturesOperations operations + :vartype features: azure.mgmt.resource.features.v2021_07_01.operations.FeaturesOperations + :ivar subscription_feature_registrations: SubscriptionFeatureRegistrationsOperations operations + :vartype subscription_feature_registrations: + azure.mgmt.resource.features.v2021_07_01.operations.SubscriptionFeatureRegistrationsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = FeatureClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize) + self.subscription_feature_registrations = SubscriptionFeatureRegistrationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "FeatureClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7da72b39ac776d1b0c2660b3c698b6eb2635c1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_vendor.py @@ -0,0 +1,48 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import List, TYPE_CHECKING, cast + +from azure.core.pipeline.transport import HttpRequest + +from ._configuration import FeatureClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core import PipelineClient + + from .._serialization import Deserializer, Serializer + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) + + +class FeatureClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "PipelineClient" + _config: FeatureClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..38ced0793f4166879d6ef8932a3e97f0cf1f3239 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "23.0.1" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43af45c2778fdf0e798a37814a099d9a1e1012e3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._feature_client import FeatureClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeatureClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..1b19be7b85851227f56c5f17ac0d5e0d119649ac --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class FeatureClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for FeatureClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(FeatureClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", "2021-07-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_feature_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_feature_client.py new file mode 100644 index 0000000000000000000000000000000000000000..761eba8c7cbe0784d9f107a9e891339762163d04 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_feature_client.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import FeatureClientConfiguration +from .operations import FeatureClientOperationsMixin, FeaturesOperations, SubscriptionFeatureRegistrationsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class FeatureClient(FeatureClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """Azure Feature Exposure Control (AFEC) provides a mechanism for the resource providers to + control feature exposure to users. Resource providers typically use this mechanism to provide + public/private preview for new features prior to making them generally available. Users need to + explicitly register for AFEC features to get access to such functionality. + + :ivar features: FeaturesOperations operations + :vartype features: azure.mgmt.resource.features.v2021_07_01.aio.operations.FeaturesOperations + :ivar subscription_feature_registrations: SubscriptionFeatureRegistrationsOperations operations + :vartype subscription_feature_registrations: + azure.mgmt.resource.features.v2021_07_01.aio.operations.SubscriptionFeatureRegistrationsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2021-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = FeatureClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize) + self.subscription_feature_registrations = SubscriptionFeatureRegistrationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "FeatureClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..c93c7557db14f7faefeb7948b8db3f8b175b023f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/_vendor.py @@ -0,0 +1,28 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import TYPE_CHECKING + +from azure.core.pipeline.transport import HttpRequest + +from ._configuration import FeatureClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core import AsyncPipelineClient + + from ..._serialization import Deserializer, Serializer + + +class FeatureClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "AsyncPipelineClient" + _config: FeatureClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d90f2d645416b0eb9e6ec4f66754edc45dc024f5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/operations/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import FeatureClientOperationsMixin +from ._operations import FeaturesOperations +from ._operations import SubscriptionFeatureRegistrationsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeatureClientOperationsMixin", + "FeaturesOperations", + "SubscriptionFeatureRegistrationsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..ee4351ce486bbd1fac088dea0574752a86be2a9c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/operations/_operations.py @@ -0,0 +1,982 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_feature_list_operations_request, + build_features_get_request, + build_features_list_all_request, + build_features_list_request, + build_features_register_request, + build_features_unregister_request, + build_subscription_feature_registrations_create_or_update_request, + build_subscription_feature_registrations_delete_request, + build_subscription_feature_registrations_get_request, + build_subscription_feature_registrations_list_all_by_subscription_request, + build_subscription_feature_registrations_list_by_subscription_request, +) +from .._vendor import FeatureClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class FeatureClientOperationsMixin(FeatureClientMixinABC): + @distributed_trace + def list_operations(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + """Lists all of the available Microsoft.Features REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.v2021_07_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_feature_list_operations_request( + api_version=api_version, + template_url=self.list_operations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_operations.metadata = {"url": "/providers/Microsoft.Features/operations"} + + +class FeaturesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.features.v2021_07_01.aio.FeatureClient`'s + :attr:`features` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_all(self, **kwargs: Any) -> AsyncIterable["_models.FeatureResult"]: + """Gets all the preview features that are available through AFEC for the subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_features_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_all.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_all.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/features"} + + @distributed_trace + def list(self, resource_provider_namespace: str, **kwargs: Any) -> AsyncIterable["_models.FeatureResult"]: + """Gets all the preview features in a provider namespace that are available through AFEC for the + subscription. + + :param resource_provider_namespace: The namespace of the resource provider for getting + features. Required. + :type resource_provider_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_features_list_request( + resource_provider_namespace=resource_provider_namespace, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features" + } + + @distributed_trace_async + async def get(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Gets the preview feature with the specified name. + + :param resource_provider_namespace: The resource provider namespace for the feature. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to get. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_get_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}" + } + + @distributed_trace_async + async def register( + self, resource_provider_namespace: str, feature_name: str, **kwargs: Any + ) -> _models.FeatureResult: + """Registers the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to register. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_register_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.register.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + register.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register" + } + + @distributed_trace_async + async def unregister( + self, resource_provider_namespace: str, feature_name: str, **kwargs: Any + ) -> _models.FeatureResult: + """Unregisters the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to unregister. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_unregister_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.unregister.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + unregister.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister" + } + + +class SubscriptionFeatureRegistrationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.features.v2021_07_01.aio.FeatureClient`'s + :attr:`subscription_feature_registrations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, provider_namespace: str, feature_name: str, **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Returns a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) + + request = build_subscription_feature_registrations_get_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}" + } + + @overload + async def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[_models.SubscriptionFeatureRegistration] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Default value is None. + :type subscription_feature_registration_type: + ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[IO] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Default value is None. + :type subscription_feature_registration_type: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[Union[_models.SubscriptionFeatureRegistration, IO]] = None, + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Is either a SubscriptionFeatureRegistration type or a IO type. Default value is None. + :type subscription_feature_registration_type: + ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(subscription_feature_registration_type, (IO, bytes)): + _content = subscription_feature_registration_type + else: + if subscription_feature_registration_type is not None: + _json = self._serialize.body(subscription_feature_registration_type, "SubscriptionFeatureRegistration") + else: + _json = None + + request = build_subscription_feature_registrations_create_or_update_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}" + } + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, provider_namespace: str, feature_name: str, **kwargs: Any + ) -> None: + """Deletes a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_subscription_feature_registrations_delete_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}" + } + + @distributed_trace + def list_by_subscription( + self, provider_namespace: str, **kwargs: Any + ) -> AsyncIterable["_models.SubscriptionFeatureRegistration"]: + """Returns subscription feature registrations for given subscription and provider namespace. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_subscription_feature_registrations_list_by_subscription_request( + provider_namespace=provider_namespace, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_subscription.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations" + } + + @distributed_trace + def list_all_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.SubscriptionFeatureRegistration"]: + """Returns subscription feature registrations for given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_subscription_feature_registrations_list_all_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_all_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_all_by_subscription.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/subscriptionFeatureRegistrations" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..941c11097915f513e78f8f7ecafd439c88ca7708 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/__init__.py @@ -0,0 +1,47 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import AuthorizationProfile +from ._models_py3 import ErrorDefinition +from ._models_py3 import ErrorResponse +from ._models_py3 import FeatureOperationsListResult +from ._models_py3 import FeatureProperties +from ._models_py3 import FeatureResult +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import ProxyResource +from ._models_py3 import SubscriptionFeatureRegistration +from ._models_py3 import SubscriptionFeatureRegistrationList +from ._models_py3 import SubscriptionFeatureRegistrationProperties + +from ._feature_client_enums import SubscriptionFeatureRegistrationApprovalType +from ._feature_client_enums import SubscriptionFeatureRegistrationState +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AuthorizationProfile", + "ErrorDefinition", + "ErrorResponse", + "FeatureOperationsListResult", + "FeatureProperties", + "FeatureResult", + "Operation", + "OperationDisplay", + "OperationListResult", + "ProxyResource", + "SubscriptionFeatureRegistration", + "SubscriptionFeatureRegistrationList", + "SubscriptionFeatureRegistrationProperties", + "SubscriptionFeatureRegistrationApprovalType", + "SubscriptionFeatureRegistrationState", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/_feature_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/_feature_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..6fc564d1483772034ca03d73bd5953d812d20ca5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/_feature_client_enums.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class SubscriptionFeatureRegistrationApprovalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The feature approval type.""" + + NOT_SPECIFIED = "NotSpecified" + APPROVAL_REQUIRED = "ApprovalRequired" + AUTO_APPROVAL = "AutoApproval" + + +class SubscriptionFeatureRegistrationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The state.""" + + NOT_SPECIFIED = "NotSpecified" + NOT_REGISTERED = "NotRegistered" + PENDING = "Pending" + REGISTERING = "Registering" + REGISTERED = "Registered" + UNREGISTERING = "Unregistering" + UNREGISTERED = "Unregistered" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..28eca6eb4154d0581ac7ef2890be38b224a812c3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/_models_py3.py @@ -0,0 +1,527 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class AuthorizationProfile(_serialization.Model): + """Authorization Profile. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar requested_time: The requested time. + :vartype requested_time: ~datetime.datetime + :ivar requester: The requester. + :vartype requester: str + :ivar requester_object_id: The requester object id. + :vartype requester_object_id: str + :ivar approved_time: The approved time. + :vartype approved_time: ~datetime.datetime + :ivar approver: The approver. + :vartype approver: str + """ + + _validation = { + "requested_time": {"readonly": True}, + "requester": {"readonly": True}, + "requester_object_id": {"readonly": True}, + "approved_time": {"readonly": True}, + "approver": {"readonly": True}, + } + + _attribute_map = { + "requested_time": {"key": "requestedTime", "type": "iso-8601"}, + "requester": {"key": "requester", "type": "str"}, + "requester_object_id": {"key": "requesterObjectId", "type": "str"}, + "approved_time": {"key": "approvedTime", "type": "iso-8601"}, + "approver": {"key": "approver", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.requested_time = None + self.requester = None + self.requester_object_id = None + self.approved_time = None + self.approver = None + + +class ErrorDefinition(_serialization.Model): + """Error definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: Service specific error code which serves as the substatus for the HTTP error code. + :vartype code: str + :ivar message: Description of the error. + :vartype message: str + :ivar details: Internal error details. + :vartype details: list[~azure.mgmt.resource.features.v2021_07_01.models.ErrorDefinition] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDefinition]"}, + } + + def __init__(self, *, details: Optional[List["_models.ErrorDefinition"]] = None, **kwargs: Any) -> None: + """ + :keyword details: Internal error details. + :paramtype details: list[~azure.mgmt.resource.features.v2021_07_01.models.ErrorDefinition] + """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.details = details + + +class ErrorResponse(_serialization.Model): + """Error response indicates that the service is not able to process the incoming request. + + :ivar error: The error details. + :vartype error: ~azure.mgmt.resource.features.v2021_07_01.models.ErrorDefinition + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDefinition"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDefinition"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error details. + :paramtype error: ~azure.mgmt.resource.features.v2021_07_01.models.ErrorDefinition + """ + super().__init__(**kwargs) + self.error = error + + +class FeatureOperationsListResult(_serialization.Model): + """List of previewed features. + + :ivar value: The array of features. + :vartype value: list[~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[FeatureResult]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.FeatureResult"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: The array of features. + :paramtype value: list[~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class FeatureProperties(_serialization.Model): + """Information about feature. + + :ivar state: The registration state of the feature for the subscription. + :vartype state: str + """ + + _attribute_map = { + "state": {"key": "state", "type": "str"}, + } + + def __init__(self, *, state: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword state: The registration state of the feature for the subscription. + :paramtype state: str + """ + super().__init__(**kwargs) + self.state = state + + +class FeatureResult(_serialization.Model): + """Previewed feature information. + + :ivar name: The name of the feature. + :vartype name: str + :ivar properties: Properties of the previewed feature. + :vartype properties: ~azure.mgmt.resource.features.v2021_07_01.models.FeatureProperties + :ivar id: The resource ID of the feature. + :vartype id: str + :ivar type: The resource type of the feature. + :vartype type: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "FeatureProperties"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + properties: Optional["_models.FeatureProperties"] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + type: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of the feature. + :paramtype name: str + :keyword properties: Properties of the previewed feature. + :paramtype properties: ~azure.mgmt.resource.features.v2021_07_01.models.FeatureProperties + :keyword id: The resource ID of the feature. + :paramtype id: str + :keyword type: The resource type of the feature. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.properties = properties + self.id = id + self.type = type + + +class Operation(_serialization.Model): + """Microsoft.Features operation. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.resource.features.v2021_07_01.models.OperationDisplay + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + } + + def __init__( + self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any + ) -> None: + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: The object that represents the operation. + :paramtype display: ~azure.mgmt.resource.features.v2021_07_01.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = name + self.display = display + + +class OperationDisplay(_serialization.Model): + """The object that represents the operation. + + :ivar provider: Service provider: Microsoft.Features. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + """ + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Service provider: Microsoft.Features. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. + :paramtype resource: str + :keyword operation: Operation type: Read, write, delete, etc. + :paramtype operation: str + """ + super().__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + + +class OperationListResult(_serialization.Model): + """Result of the request to list Microsoft.Features operations. It contains a list of operations + and a URL link to get the next set of results. + + :ivar value: List of Microsoft.Features operations. + :vartype value: list[~azure.mgmt.resource.features.v2021_07_01.models.Operation] + :ivar next_link: URL to get the next set of operation list results if there are any. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: List of Microsoft.Features operations. + :paramtype value: list[~azure.mgmt.resource.features.v2021_07_01.models.Operation] + :keyword next_link: URL to get the next set of operation list results if there are any. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ProxyResource(_serialization.Model): + """An Azure proxy resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Azure resource Id. + :vartype id: str + :ivar name: Azure resource name. + :vartype name: str + :ivar type: Azure resource type. + :vartype type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class SubscriptionFeatureRegistration(ProxyResource): + """Subscription feature registration details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Azure resource Id. + :vartype id: str + :ivar name: Azure resource name. + :vartype name: str + :ivar type: Azure resource type. + :vartype type: str + :ivar properties: + :vartype properties: + ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistrationProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "SubscriptionFeatureRegistrationProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.SubscriptionFeatureRegistrationProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: + :paramtype properties: + ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistrationProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class SubscriptionFeatureRegistrationList(_serialization.Model): + """The list of subscription feature registrations. + + :ivar next_link: The link used to get the next page of subscription feature registrations list. + :vartype next_link: str + :ivar value: The list of subscription feature registrations. + :vartype value: + list[~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration] + """ + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[SubscriptionFeatureRegistration]"}, + } + + def __init__( + self, + *, + next_link: Optional[str] = None, + value: Optional[List["_models.SubscriptionFeatureRegistration"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword next_link: The link used to get the next page of subscription feature registrations + list. + :paramtype next_link: str + :keyword value: The list of subscription feature registrations. + :paramtype value: + list[~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = value + + +class SubscriptionFeatureRegistrationProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """SubscriptionFeatureRegistrationProperties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar tenant_id: The tenantId. + :vartype tenant_id: str + :ivar subscription_id: The subscriptionId. + :vartype subscription_id: str + :ivar feature_name: The featureName. + :vartype feature_name: str + :ivar display_name: The featureDisplayName. + :vartype display_name: str + :ivar provider_namespace: The providerNamespace. + :vartype provider_namespace: str + :ivar state: The state. Known values are: "NotSpecified", "NotRegistered", "Pending", + "Registering", "Registered", "Unregistering", and "Unregistered". + :vartype state: str or + ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistrationState + :ivar authorization_profile: Authorization Profile. + :vartype authorization_profile: + ~azure.mgmt.resource.features.v2021_07_01.models.AuthorizationProfile + :ivar metadata: Key-value pairs for meta data. + :vartype metadata: dict[str, str] + :ivar release_date: The feature release date. + :vartype release_date: ~datetime.datetime + :ivar registration_date: The feature registration date. + :vartype registration_date: ~datetime.datetime + :ivar documentation_link: The feature documentation link. + :vartype documentation_link: str + :ivar approval_type: The feature approval type. Known values are: "NotSpecified", + "ApprovalRequired", and "AutoApproval". + :vartype approval_type: str or + ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistrationApprovalType + :ivar should_feature_display_in_portal: Indicates whether feature should be displayed in + Portal. + :vartype should_feature_display_in_portal: bool + :ivar description: The feature description. + :vartype description: str + """ + + _validation = { + "tenant_id": {"readonly": True}, + "subscription_id": {"readonly": True}, + "feature_name": {"readonly": True}, + "display_name": {"readonly": True}, + "provider_namespace": {"readonly": True}, + "release_date": {"readonly": True}, + "registration_date": {"readonly": True}, + "documentation_link": {"readonly": True, "max_length": 1000}, + "approval_type": {"readonly": True}, + "description": {"max_length": 1000}, + } + + _attribute_map = { + "tenant_id": {"key": "tenantId", "type": "str"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + "feature_name": {"key": "featureName", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "provider_namespace": {"key": "providerNamespace", "type": "str"}, + "state": {"key": "state", "type": "str"}, + "authorization_profile": {"key": "authorizationProfile", "type": "AuthorizationProfile"}, + "metadata": {"key": "metadata", "type": "{str}"}, + "release_date": {"key": "releaseDate", "type": "iso-8601"}, + "registration_date": {"key": "registrationDate", "type": "iso-8601"}, + "documentation_link": {"key": "documentationLink", "type": "str"}, + "approval_type": {"key": "approvalType", "type": "str"}, + "should_feature_display_in_portal": {"key": "shouldFeatureDisplayInPortal", "type": "bool"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__( + self, + *, + state: Optional[Union[str, "_models.SubscriptionFeatureRegistrationState"]] = None, + authorization_profile: Optional["_models.AuthorizationProfile"] = None, + metadata: Optional[Dict[str, str]] = None, + should_feature_display_in_portal: bool = False, + description: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword state: The state. Known values are: "NotSpecified", "NotRegistered", "Pending", + "Registering", "Registered", "Unregistering", and "Unregistered". + :paramtype state: str or + ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistrationState + :keyword authorization_profile: Authorization Profile. + :paramtype authorization_profile: + ~azure.mgmt.resource.features.v2021_07_01.models.AuthorizationProfile + :keyword metadata: Key-value pairs for meta data. + :paramtype metadata: dict[str, str] + :keyword should_feature_display_in_portal: Indicates whether feature should be displayed in + Portal. + :paramtype should_feature_display_in_portal: bool + :keyword description: The feature description. + :paramtype description: str + """ + super().__init__(**kwargs) + self.tenant_id = None + self.subscription_id = None + self.feature_name = None + self.display_name = None + self.provider_namespace = None + self.state = state + self.authorization_profile = authorization_profile + self.metadata = metadata + self.release_date = None + self.registration_date = None + self.documentation_link = None + self.approval_type = None + self.should_feature_display_in_portal = should_feature_display_in_portal + self.description = description diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d90f2d645416b0eb9e6ec4f66754edc45dc024f5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/operations/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import FeatureClientOperationsMixin +from ._operations import FeaturesOperations +from ._operations import SubscriptionFeatureRegistrationsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "FeatureClientOperationsMixin", + "FeaturesOperations", + "SubscriptionFeatureRegistrationsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..0eb0506f9ff9450de2e103f8e41afceac7cb94de --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/operations/_operations.py @@ -0,0 +1,1283 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import FeatureClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_feature_list_operations_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Features/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_list_all_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Features/features") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_list_request(resource_provider_namespace: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_get_request( + resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_register_request( + resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_unregister_request( + resource_provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscription_feature_registrations_get_request( + provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscription_feature_registrations_create_or_update_request( + provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscription_feature_registrations_delete_request( + provider_namespace: str, feature_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), + "featureName": _SERIALIZER.url("feature_name", feature_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscription_feature_registrations_list_by_subscription_request( + provider_namespace: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerNamespace": _SERIALIZER.url("provider_namespace", provider_namespace, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscription_feature_registrations_list_all_by_subscription_request( + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Features/subscriptionFeatureRegistrations" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class FeatureClientOperationsMixin(FeatureClientMixinABC): + @distributed_trace + def list_operations(self, **kwargs: Any) -> Iterable["_models.Operation"]: + """Lists all of the available Microsoft.Features REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.v2021_07_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_feature_list_operations_request( + api_version=api_version, + template_url=self.list_operations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_operations.metadata = {"url": "/providers/Microsoft.Features/operations"} + + +class FeaturesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.features.v2021_07_01.FeatureClient`'s + :attr:`features` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_all(self, **kwargs: Any) -> Iterable["_models.FeatureResult"]: + """Gets all the preview features that are available through AFEC for the subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_features_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_all.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_all.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/features"} + + @distributed_trace + def list(self, resource_provider_namespace: str, **kwargs: Any) -> Iterable["_models.FeatureResult"]: + """Gets all the preview features in a provider namespace that are available through AFEC for the + subscription. + + :param resource_provider_namespace: The namespace of the resource provider for getting + features. Required. + :type resource_provider_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FeatureResult or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.FeatureOperationsListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_features_list_request( + resource_provider_namespace=resource_provider_namespace, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("FeatureOperationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features" + } + + @distributed_trace + def get(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Gets the preview feature with the specified name. + + :param resource_provider_namespace: The resource provider namespace for the feature. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to get. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_get_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}" + } + + @distributed_trace + def register(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Registers the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to register. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_register_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.register.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + register.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register" + } + + @distributed_trace + def unregister(self, resource_provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.FeatureResult: + """Unregisters the preview feature for the subscription. + + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param feature_name: The name of the feature to unregister. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FeatureResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.FeatureResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.FeatureResult] = kwargs.pop("cls", None) + + request = build_features_unregister_request( + resource_provider_namespace=resource_provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.unregister.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FeatureResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + unregister.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister" + } + + +class SubscriptionFeatureRegistrationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.features.v2021_07_01.FeatureClient`'s + :attr:`subscription_feature_registrations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, provider_namespace: str, feature_name: str, **kwargs: Any) -> _models.SubscriptionFeatureRegistration: + """Returns a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) + + request = build_subscription_feature_registrations_get_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}" + } + + @overload + def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[_models.SubscriptionFeatureRegistration] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Default value is None. + :type subscription_feature_registration_type: + ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[IO] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Default value is None. + :type subscription_feature_registration_type: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + provider_namespace: str, + feature_name: str, + subscription_feature_registration_type: Optional[Union[_models.SubscriptionFeatureRegistration, IO]] = None, + **kwargs: Any + ) -> _models.SubscriptionFeatureRegistration: + """Create or update a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :param subscription_feature_registration_type: Subscription Feature Registration Type details. + Is either a SubscriptionFeatureRegistration type or a IO type. Default value is None. + :type subscription_feature_registration_type: + ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SubscriptionFeatureRegistration or the result of cls(response) + :rtype: ~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SubscriptionFeatureRegistration] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(subscription_feature_registration_type, (IO, bytes)): + _content = subscription_feature_registration_type + else: + if subscription_feature_registration_type is not None: + _json = self._serialize.body(subscription_feature_registration_type, "SubscriptionFeatureRegistration") + else: + _json = None + + request = build_subscription_feature_registrations_create_or_update_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("SubscriptionFeatureRegistration", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}" + } + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, provider_namespace: str, feature_name: str, **kwargs: Any + ) -> None: + """Deletes a feature registration. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :param feature_name: The feature name. Required. + :type feature_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_subscription_feature_registrations_delete_request( + provider_namespace=provider_namespace, + feature_name=feature_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations/{featureName}" + } + + @distributed_trace + def list_by_subscription( + self, provider_namespace: str, **kwargs: Any + ) -> Iterable["_models.SubscriptionFeatureRegistration"]: + """Returns subscription feature registrations for given subscription and provider namespace. + + :param provider_namespace: The provider namespace. Required. + :type provider_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_subscription_feature_registrations_list_by_subscription_request( + provider_namespace=provider_namespace, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_subscription.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/featureProviders/{providerNamespace}/subscriptionFeatureRegistrations" + } + + @distributed_trace + def list_all_by_subscription(self, **kwargs: Any) -> Iterable["_models.SubscriptionFeatureRegistration"]: + """Returns subscription feature registrations for given subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SubscriptionFeatureRegistration or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.features.v2021_07_01.models.SubscriptionFeatureRegistration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01")) + cls: ClsType[_models.SubscriptionFeatureRegistrationList] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_subscription_feature_registrations_list_all_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_all_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("SubscriptionFeatureRegistrationList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_all_by_subscription.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Features/subscriptionFeatureRegistrations" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/features/v2021_07_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cfc482362343714a10a617e782183b50f5bd7974 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._management_link_client import ManagementLinkClient +__all__ = ['ManagementLinkClient'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..f7fb540fd7813b948d50e32f7095fd70a195acdc --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class ManagementLinkClientConfiguration(Configuration): + """Configuration for ManagementLinkClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(ManagementLinkClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'azure-mgmt-resource/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/aio/_management_link_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/aio/_management_link_client.py new file mode 100644 index 0000000000000000000000000000000000000000..4f40ed408263dd20a6b61f76d5c091825fee8950 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/aio/_management_link_client.py @@ -0,0 +1,129 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.mgmt.core import AsyncARMPipelineClient +from azure.profiles import KnownProfiles, ProfileDefinition +from azure.profiles.multiapiclient import MultiApiClientMixin + +from .._serialization import Deserializer, Serializer +from ._configuration import ManagementLinkClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class _SDKClient(object): + def __init__(self, *args, **kwargs): + """This is a fake class to support current implemetation of MultiApiClientMixin." + Will be removed in final version of multiapi azure-core based client + """ + pass + +class ManagementLinkClient(MultiApiClientMixin, _SDKClient): + """Azure resources can be linked together to form logical relationships. You can establish links between resources belonging to different resource groups. However, all the linked resources must belong to the same subscription. Each resource can be linked to 50 other resources. If any of the linked resources are deleted or moved, the link owner must clean up the remaining link. + + This ready contains multiple API versions, to help you deal with all of the Azure clouds + (Azure Stack, Azure Government, Azure China, etc.). + By default, it uses the latest API version available on public Azure. + For production, you should stick to a particular api-version and/or profile. + The profile sets a mapping between an operation group and its API version. + The api-version parameter sets the default API version if the operation + group is not described in the profile. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param api_version: API version to use if no profile is provided, or if missing in profile. + :type api_version: str + :param base_url: Service URL + :type base_url: str + :param profile: A profile definition, from KnownProfiles to dict. + :type profile: azure.profiles.KnownProfiles + """ + + DEFAULT_API_VERSION = '2016-09-01' + _PROFILE_TAG = "azure.mgmt.resource.links.ManagementLinkClient" + LATEST_PROFILE = ProfileDefinition({ + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + }}, + _PROFILE_TAG + " latest" + ) + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + api_version: Optional[str] = None, + base_url: str = "https://management.azure.com", + profile: KnownProfiles = KnownProfiles.default, + **kwargs: Any + ) -> None: + self._config = ManagementLinkClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + super(ManagementLinkClient, self).__init__( + api_version=api_version, + profile=profile + ) + + @classmethod + def _models_dict(cls, api_version): + return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} + + @classmethod + def models(cls, api_version=DEFAULT_API_VERSION): + """Module depends on the API version: + + * 2016-09-01: :mod:`v2016_09_01.models` + """ + if api_version == '2016-09-01': + from ..v2016_09_01 import models + return models + raise ValueError("API version {} is not available".format(api_version)) + + @property + def operations(self): + """Instance depends on the API version: + + * 2016-09-01: :class:`Operations` + """ + api_version = self._get_api_version('operations') + if api_version == '2016-09-01': + from ..v2016_09_01.aio.operations import Operations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def resource_links(self): + """Instance depends on the API version: + + * 2016-09-01: :class:`ResourceLinksOperations` + """ + api_version = self._get_api_version('resource_links') + if api_version == '2016-09-01': + from ..v2016_09_01.aio.operations import ResourceLinksOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'resource_links'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + async def close(self): + await self._client.close() + async def __aenter__(self): + await self._client.__aenter__() + return self + async def __aexit__(self, *exc_details): + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a481ab1618335130aa72d55311df346a7e00adab --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._management_link_client import ManagementLinkClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLinkClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..93af381b41488ec50ee31ad3ae313a2ffc84960a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class ManagementLinkClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ManagementLinkClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ManagementLinkClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", "2016-09-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_management_link_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_management_link_client.py new file mode 100644 index 0000000000000000000000000000000000000000..cc634e4ed7e3dfbcfbfd5d7e6e5d98f58485f932 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_management_link_client.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import ManagementLinkClientConfiguration +from .operations import Operations, ResourceLinksOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class ManagementLinkClient: # pylint: disable=client-accepts-api-version-keyword + """Azure resources can be linked together to form logical relationships. You can establish links + between resources belonging to different resource groups. However, all the linked resources + must belong to the same subscription. Each resource can be linked to 50 other resources. If any + of the linked resources are deleted or moved, the link owner must clean up the remaining link. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.resource.links.v2016_09_01.operations.Operations + :ivar resource_links: ResourceLinksOperations operations + :vartype resource_links: + azure.mgmt.resource.links.v2016_09_01.operations.ResourceLinksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ManagementLinkClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.resource_links = ResourceLinksOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "ManagementLinkClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0df84f5319f2e522d0fec4553e2e8b04bf904a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_vendor.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import List, cast + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..38ced0793f4166879d6ef8932a3e97f0cf1f3239 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "23.0.1" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92d287671ad10492db5ba1b45a6517e2c3d4eeda --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._management_link_client import ManagementLinkClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLinkClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..08fdc0c236c5b24c04ee8eca966843d77573caad --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementLinkClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ManagementLinkClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ManagementLinkClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", "2016-09-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/_management_link_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/_management_link_client.py new file mode 100644 index 0000000000000000000000000000000000000000..e8a993d9f3c9f4912091c922048c0035175efe54 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/_management_link_client.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import ManagementLinkClientConfiguration +from .operations import Operations, ResourceLinksOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementLinkClient: # pylint: disable=client-accepts-api-version-keyword + """Azure resources can be linked together to form logical relationships. You can establish links + between resources belonging to different resource groups. However, all the linked resources + must belong to the same subscription. Each resource can be linked to 50 other resources. If any + of the linked resources are deleted or moved, the link owner must clean up the remaining link. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.resource.links.v2016_09_01.aio.operations.Operations + :ivar resource_links: ResourceLinksOperations operations + :vartype resource_links: + azure.mgmt.resource.links.v2016_09_01.aio.operations.ResourceLinksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ManagementLinkClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.resource_links = ResourceLinksOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "ManagementLinkClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..387277369a5e709a3145dd2af1f1100ffb91d1ad --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import Operations +from ._operations import ResourceLinksOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "ResourceLinksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b17ed03bcfbcd7c78ec402081a5d7be239920666 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/operations/_operations.py @@ -0,0 +1,587 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_operations_list_request, + build_resource_links_create_or_update_request, + build_resource_links_delete_request, + build_resource_links_get_request, + build_resource_links_list_at_source_scope_request, + build_resource_links_list_at_subscription_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.links.v2016_09_01.aio.ManagementLinkClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + """Lists all of the available Microsoft.Resources REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.links.v2016_09_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_operations_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Resources/operations"} + + +class ResourceLinksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.links.v2016_09_01.aio.ManagementLinkClient`'s + :attr:`resource_links` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete(self, link_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Deletes a resource link with the specified ID. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_resource_links_delete_request( + link_id=link_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/{linkId}"} + + @overload + async def create_or_update( + self, link_id: str, parameters: _models.ResourceLink, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Required. + :type parameters: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, link_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, link_id: str, parameters: Union[_models.ResourceLink, IO], **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Is either a + ResourceLink type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ResourceLink") + + request = build_resource_links_create_or_update_request( + link_id=link_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ResourceLink", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ResourceLink", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update.metadata = {"url": "/{linkId}"} + + @distributed_trace_async + async def get(self, link_id: str, **kwargs: Any) -> _models.ResourceLink: + """Gets a resource link with the specified ID. + + :param link_id: The fully qualified Id of the resource link. For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) + + request = build_resource_links_get_request( + link_id=link_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceLink", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{linkId}"} + + @distributed_trace + def list_at_subscription( + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ResourceLink"]: + """Gets all the linked resources for the subscription. + + :param filter: The filter to apply on the list resource links operation. The supported filter + for list resource links is targetId. For example, $filter=targetId eq {value}. Default value is + None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceLink or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_resource_links_list_at_subscription_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ResourceLinkResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/links"} + + @distributed_trace + def list_at_source_scope( + self, scope: str, filter: Literal["atScope()"] = "atScope()", **kwargs: Any + ) -> AsyncIterable["_models.ResourceLink"]: + """Gets a list of resource links at and below the specified source scope. + + :param scope: The fully qualified ID of the scope for getting the resource links. For example, + to list resource links at and under a resource group, set the scope to + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup. Required. + :type scope: str + :param filter: The filter to apply when getting resource links. To get links only at the + specified scope (not below the scope), use Filter.atScope(). Known values are "atScope()" and + None. Default value is "atScope()". + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceLink or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_resource_links_list_at_source_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_at_source_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ResourceLinkResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_at_source_scope.metadata = {"url": "/{scope}/providers/Microsoft.Resources/links"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f5281fa67841d55819af1de4b302d91a03a862b5 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/models/__init__.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import ResourceLink +from ._models_py3 import ResourceLinkFilter +from ._models_py3 import ResourceLinkProperties +from ._models_py3 import ResourceLinkResult +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operation", + "OperationDisplay", + "OperationListResult", + "ResourceLink", + "ResourceLinkFilter", + "ResourceLinkProperties", + "ResourceLinkResult", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..9b406e99aec002882bbdcacd2b75085276a13d4a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/models/_models_py3.py @@ -0,0 +1,257 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, List, Optional, TYPE_CHECKING + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class Operation(_serialization.Model): + """Microsoft.Resources operation. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.resource.links.v2016_09_01.models.OperationDisplay + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + } + + def __init__( + self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any + ) -> None: + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: The object that represents the operation. + :paramtype display: ~azure.mgmt.resource.links.v2016_09_01.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = name + self.display = display + + +class OperationDisplay(_serialization.Model): + """The object that represents the operation. + + :ivar provider: Service provider: Microsoft.Resources. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + :ivar description: Description of the operation. + :vartype description: str + """ + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Service provider: Microsoft.Resources. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. + :paramtype resource: str + :keyword operation: Operation type: Read, write, delete, etc. + :paramtype operation: str + :keyword description: Description of the operation. + :paramtype description: str + """ + super().__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + self.description = description + + +class OperationListResult(_serialization.Model): + """Result of the request to list Microsoft.Resources operations. It contains a list of operations + and a URL link to get the next set of results. + + :ivar value: List of Microsoft.Resources operations. + :vartype value: list[~azure.mgmt.resource.links.v2016_09_01.models.Operation] + :ivar next_link: URL to get the next set of operation list results if there are any. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: List of Microsoft.Resources operations. + :paramtype value: list[~azure.mgmt.resource.links.v2016_09_01.models.Operation] + :keyword next_link: URL to get the next set of operation list results if there are any. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ResourceLink(_serialization.Model): + """The resource link. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The fully qualified ID of the resource link. + :vartype id: str + :ivar name: The name of the resource link. + :vartype name: str + :ivar type: The resource link object. + :vartype type: JSON + :ivar properties: Properties for resource link. + :vartype properties: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLinkProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "object"}, + "properties": {"key": "properties", "type": "ResourceLinkProperties"}, + } + + def __init__(self, *, properties: Optional["_models.ResourceLinkProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: Properties for resource link. + :paramtype properties: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLinkProperties + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.properties = properties + + +class ResourceLinkFilter(_serialization.Model): + """Resource link filter. + + All required parameters must be populated in order to send to Azure. + + :ivar target_id: The ID of the target resource. Required. + :vartype target_id: str + """ + + _validation = { + "target_id": {"required": True}, + } + + _attribute_map = { + "target_id": {"key": "targetId", "type": "str"}, + } + + def __init__(self, *, target_id: str, **kwargs: Any) -> None: + """ + :keyword target_id: The ID of the target resource. Required. + :paramtype target_id: str + """ + super().__init__(**kwargs) + self.target_id = target_id + + +class ResourceLinkProperties(_serialization.Model): + """The resource link properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar source_id: The fully qualified ID of the source resource in the link. + :vartype source_id: str + :ivar target_id: The fully qualified ID of the target resource in the link. Required. + :vartype target_id: str + :ivar notes: Notes about the resource link. + :vartype notes: str + """ + + _validation = { + "source_id": {"readonly": True}, + "target_id": {"required": True}, + } + + _attribute_map = { + "source_id": {"key": "sourceId", "type": "str"}, + "target_id": {"key": "targetId", "type": "str"}, + "notes": {"key": "notes", "type": "str"}, + } + + def __init__(self, *, target_id: str, notes: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword target_id: The fully qualified ID of the target resource in the link. Required. + :paramtype target_id: str + :keyword notes: Notes about the resource link. + :paramtype notes: str + """ + super().__init__(**kwargs) + self.source_id = None + self.target_id = target_id + self.notes = notes + + +class ResourceLinkResult(_serialization.Model): + """List of resource links. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar value: An array of resource links. Required. + :vartype value: list[~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[ResourceLink]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: List["_models.ResourceLink"], **kwargs: Any) -> None: + """ + :keyword value: An array of resource links. Required. + :paramtype value: list[~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink] + """ + super().__init__(**kwargs) + self.value = value + self.next_link = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..387277369a5e709a3145dd2af1f1100ffb91d1ad --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import Operations +from ._operations import ResourceLinksOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "ResourceLinksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b029b191d51cdc6f08536de0a3235163aedaeb70 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/operations/_operations.py @@ -0,0 +1,723 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_operations_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Resources/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_links_delete_request(link_id: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + # Construct URL + _url = kwargs.pop("template_url", "/{linkId}") + path_format_arguments = { + "linkId": _SERIALIZER.url("link_id", link_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_resource_links_create_or_update_request(link_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{linkId}") + path_format_arguments = { + "linkId": _SERIALIZER.url("link_id", link_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_links_get_request(link_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{linkId}") + path_format_arguments = { + "linkId": _SERIALIZER.url("link_id", link_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_links_list_at_subscription_request( + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/links") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_resource_links_list_at_source_scope_request( + scope: str, *, filter: Literal["atScope()"] = "atScope()", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Resources/links") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.links.v2016_09_01.ManagementLinkClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: + """Lists all of the available Microsoft.Resources REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.links.v2016_09_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_operations_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Resources/operations"} + + +class ResourceLinksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.links.v2016_09_01.ManagementLinkClient`'s + :attr:`resource_links` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete(self, link_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Deletes a resource link with the specified ID. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_resource_links_delete_request( + link_id=link_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/{linkId}"} + + @overload + def create_or_update( + self, link_id: str, parameters: _models.ResourceLink, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Required. + :type parameters: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, link_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, link_id: str, parameters: Union[_models.ResourceLink, IO], **kwargs: Any + ) -> _models.ResourceLink: + """Creates or updates a resource link between the specified resources. + + :param link_id: The fully qualified ID of the resource link. Use the format, + /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/{provider-namespace}/{resource-type}/{resource-name}/Microsoft.Resources/links/{link-name}. + For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :param parameters: Parameters for creating or updating a resource link. Is either a + ResourceLink type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ResourceLink") + + request = build_resource_links_create_or_update_request( + link_id=link_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ResourceLink", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ResourceLink", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update.metadata = {"url": "/{linkId}"} + + @distributed_trace + def get(self, link_id: str, **kwargs: Any) -> _models.ResourceLink: + """Gets a resource link with the specified ID. + + :param link_id: The fully qualified Id of the resource link. For example, + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite/Microsoft.Resources/links/myLink. + Required. + :type link_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ResourceLink or the result of cls(response) + :rtype: ~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ResourceLink] = kwargs.pop("cls", None) + + request = build_resource_links_get_request( + link_id=link_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ResourceLink", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{linkId}"} + + @distributed_trace + def list_at_subscription(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.ResourceLink"]: + """Gets all the linked resources for the subscription. + + :param filter: The filter to apply on the list resource links operation. The supported filter + for list resource links is targetId. For example, $filter=targetId eq {value}. Default value is + None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceLink or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_resource_links_list_at_subscription_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ResourceLinkResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Resources/links"} + + @distributed_trace + def list_at_source_scope( + self, scope: str, filter: Literal["atScope()"] = "atScope()", **kwargs: Any + ) -> Iterable["_models.ResourceLink"]: + """Gets a list of resource links at and below the specified source scope. + + :param scope: The fully qualified ID of the scope for getting the resource links. For example, + to list resource links at and under a resource group, set the scope to + /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup. Required. + :type scope: str + :param filter: The filter to apply when getting resource links. To get links only at the + specified scope (not below the scope), use Filter.atScope(). Known values are "atScope()" and + None. Default value is "atScope()". + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceLink or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.links.v2016_09_01.models.ResourceLink] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ResourceLinkResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_resource_links_list_at_source_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_at_source_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ResourceLinkResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_at_source_scope.metadata = {"url": "/{scope}/providers/Microsoft.Resources/links"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/links/v2016_09_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c6025457e1d148a6362c7439198caee3e0b05594 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._management_lock_client import ManagementLockClient +__all__ = ['ManagementLockClient'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..23d4c356da100f4aa6c30d0d5e71fb8eb54825c3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class ManagementLockClientConfiguration(Configuration): + """Configuration for ManagementLockClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(ManagementLockClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'azure-mgmt-resource/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/aio/_management_lock_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/aio/_management_lock_client.py new file mode 100644 index 0000000000000000000000000000000000000000..97cc79ec0c194f90e9a4b511ac81d87185f21e61 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/aio/_management_lock_client.py @@ -0,0 +1,136 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.mgmt.core import AsyncARMPipelineClient +from azure.profiles import KnownProfiles, ProfileDefinition +from azure.profiles.multiapiclient import MultiApiClientMixin + +from .._serialization import Deserializer, Serializer +from ._configuration import ManagementLockClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class _SDKClient(object): + def __init__(self, *args, **kwargs): + """This is a fake class to support current implemetation of MultiApiClientMixin." + Will be removed in final version of multiapi azure-core based client + """ + pass + +class ManagementLockClient(MultiApiClientMixin, _SDKClient): + """Azure resources can be locked to prevent other users in your organization from deleting or modifying resources. + + This ready contains multiple API versions, to help you deal with all of the Azure clouds + (Azure Stack, Azure Government, Azure China, etc.). + By default, it uses the latest API version available on public Azure. + For production, you should stick to a particular api-version and/or profile. + The profile sets a mapping between an operation group and its API version. + The api-version parameter sets the default API version if the operation + group is not described in the profile. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param api_version: API version to use if no profile is provided, or if missing in profile. + :type api_version: str + :param base_url: Service URL + :type base_url: str + :param profile: A profile definition, from KnownProfiles to dict. + :type profile: azure.profiles.KnownProfiles + """ + + DEFAULT_API_VERSION = '2016-09-01' + _PROFILE_TAG = "azure.mgmt.resource.locks.ManagementLockClient" + LATEST_PROFILE = ProfileDefinition({ + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + }}, + _PROFILE_TAG + " latest" + ) + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + api_version: Optional[str] = None, + base_url: str = "https://management.azure.com", + profile: KnownProfiles = KnownProfiles.default, + **kwargs: Any + ) -> None: + self._config = ManagementLockClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + super(ManagementLockClient, self).__init__( + api_version=api_version, + profile=profile + ) + + @classmethod + def _models_dict(cls, api_version): + return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} + + @classmethod + def models(cls, api_version=DEFAULT_API_VERSION): + """Module depends on the API version: + + * 2015-01-01: :mod:`v2015_01_01.models` + * 2016-09-01: :mod:`v2016_09_01.models` + """ + if api_version == '2015-01-01': + from ..v2015_01_01 import models + return models + elif api_version == '2016-09-01': + from ..v2016_09_01 import models + return models + raise ValueError("API version {} is not available".format(api_version)) + + @property + def authorization_operations(self): + """Instance depends on the API version: + + * 2016-09-01: :class:`AuthorizationOperationsOperations` + """ + api_version = self._get_api_version('authorization_operations') + if api_version == '2016-09-01': + from ..v2016_09_01.aio.operations import AuthorizationOperationsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'authorization_operations'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def management_locks(self): + """Instance depends on the API version: + + * 2015-01-01: :class:`ManagementLocksOperations` + * 2016-09-01: :class:`ManagementLocksOperations` + """ + api_version = self._get_api_version('management_locks') + if api_version == '2015-01-01': + from ..v2015_01_01.aio.operations import ManagementLocksOperations as OperationClass + elif api_version == '2016-09-01': + from ..v2016_09_01.aio.operations import ManagementLocksOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'management_locks'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + async def close(self): + await self._client.close() + async def __aenter__(self): + await self._client.__aenter__() + return self + async def __aexit__(self, *exc_details): + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4a02cc9246e62a7d7f8d2f7ff8738564f4095768 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._management_lock_client import ManagementLockClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLockClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..a73f79c5acf03023033e78f857d1fda0f4b26c03 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class ManagementLockClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ManagementLockClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-01-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ManagementLockClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", "2015-01-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_management_lock_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_management_lock_client.py new file mode 100644 index 0000000000000000000000000000000000000000..42216b03715a07d67d8a27bfce8dc6bb81c2a2b8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_management_lock_client.py @@ -0,0 +1,92 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import ManagementLockClientConfiguration +from .operations import ManagementLocksOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class ManagementLockClient: # pylint: disable=client-accepts-api-version-keyword + """ManagementLockClient. + + :ivar management_locks: ManagementLocksOperations operations + :vartype management_locks: + azure.mgmt.resource.locks.v2015_01_01.operations.ManagementLocksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2015-01-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ManagementLockClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.management_locks = ManagementLocksOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "ManagementLockClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0df84f5319f2e522d0fec4553e2e8b04bf904a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_vendor.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import List, cast + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..38ced0793f4166879d6ef8932a3e97f0cf1f3239 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "23.0.1" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..021d914862b0be2ef39c0d904d834b5b68b7a490 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._management_lock_client import ManagementLockClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLockClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..805ace13188debb3f0171914f67c62540fdcdaf7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementLockClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ManagementLockClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-01-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ManagementLockClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", "2015-01-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/_management_lock_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/_management_lock_client.py new file mode 100644 index 0000000000000000000000000000000000000000..04ae9ffc6eb64d13e5c12e203b8d84c99e5bee24 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/_management_lock_client.py @@ -0,0 +1,92 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import ManagementLockClientConfiguration +from .operations import ManagementLocksOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementLockClient: # pylint: disable=client-accepts-api-version-keyword + """ManagementLockClient. + + :ivar management_locks: ManagementLocksOperations operations + :vartype management_locks: + azure.mgmt.resource.locks.v2015_01_01.aio.operations.ManagementLocksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2015-01-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ManagementLockClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.management_locks = ManagementLocksOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "ManagementLockClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5fe90f3f763822a16947ec6c08efb625640deea1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import ManagementLocksOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLocksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd82ae5eb35ad4462736c9e549c9c6770f42f48 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/operations/_operations.py @@ -0,0 +1,1127 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_management_locks_create_or_update_at_resource_group_level_request, + build_management_locks_create_or_update_at_resource_level_request, + build_management_locks_create_or_update_at_subscription_level_request, + build_management_locks_delete_at_resource_group_level_request, + build_management_locks_delete_at_resource_level_request, + build_management_locks_delete_at_subscription_level_request, + build_management_locks_get_at_resource_group_level_request, + build_management_locks_get_request, + build_management_locks_list_at_resource_group_level_request, + build_management_locks_list_at_resource_level_request, + build_management_locks_list_at_subscription_level_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ManagementLocksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.locks.v2015_01_01.aio.ManagementLockClient`'s + :attr:`management_locks` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource group level. + + :param resource_group_name: The resource group name. Required. + :type resource_group_name: str + :param lock_name: The lock name. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource group level. + + :param resource_group_name: The resource group name. Required. + :type resource_group_name: str + :param lock_name: The lock name. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource group level. + + :param resource_group_name: The resource group name. Required. + :type resource_group_name: str + :param lock_name: The lock name. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace_async + async def delete_at_resource_group_level( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lock_name: str, **kwargs: Any + ) -> None: + """Deletes the management lock of a resource group. + + :param resource_group_name: The resource group name. Required. + :type resource_group_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace_async + async def get_at_resource_group_level( + self, resource_group_name: str, lock_name: str, **kwargs: Any + ) -> _models.ManagementLockObject: + """Gets a management lock at the resource group level. + + :param resource_group_name: The resource group name. Required. + :type resource_group_name: str + :param lock_name: The lock name. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @overload + async def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource level or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: Resource identity. Required. + :type resource_provider_namespace: str + :param parent_resource_path: Resource identity. Required. + :type parent_resource_path: str + :param resource_type: Resource identity. Required. + :type resource_type: str + :param resource_name: Resource identity. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource level or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: Resource identity. Required. + :type resource_provider_namespace: str + :param parent_resource_path: Resource identity. Required. + :type parent_resource_path: str + :param resource_type: Resource identity. Required. + :type resource_type: str + :param resource_name: Resource identity. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource level or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: Resource identity. Required. + :type resource_provider_namespace: str + :param parent_resource_path: Resource identity. Required. + :type parent_resource_path: str + :param resource_type: Resource identity. Required. + :type resource_type: str + :param resource_name: Resource identity. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Is either a + ManagementLockObject type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace_async + async def delete_at_resource_level( # pylint: disable=inconsistent-return-statements + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + **kwargs: Any + ) -> None: + """Deletes the management lock of a resource or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: Resource identity. Required. + :type resource_provider_namespace: str + :param parent_resource_path: Resource identity. Required. + :type parent_resource_path: str + :param resource_type: Resource identity. Required. + :type resource_type: str + :param resource_name: Resource identity. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @overload + async def create_or_update_at_subscription_level( + self, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the subscription level. + + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_subscription_level( + self, lock_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the subscription level. + + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_subscription_level( + self, lock_name: str, parameters: Union[_models.ManagementLockObject, IO], **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the subscription level. + + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace_async + async def delete_at_subscription_level( # pylint: disable=inconsistent-return-statements + self, lock_name: str, **kwargs: Any + ) -> None: + """Deletes the management lock of a subscription. + + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace_async + async def get(self, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: + """Gets the management lock of a scope. + + :param lock_name: Name of the management lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}"} + + @distributed_trace + def list_at_resource_group_level( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ManagementLockObject"]: + """Gets all the management locks of a resource group. + + :param resource_group_name: Resource group name. Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_resource_group_level_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks" + } + + @distributed_trace + def list_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.ManagementLockObject"]: + """Gets all the management locks of a resource or any level below resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param resource_provider_namespace: Resource identity. Required. + :type resource_provider_namespace: str + :param parent_resource_path: Resource identity. Required. + :type parent_resource_path: str + :param resource_type: Resource identity. Required. + :type resource_type: str + :param resource_name: Resource identity. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks" + } + + @distributed_trace + def list_at_subscription_level( + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ManagementLockObject"]: + """Gets all the management locks of a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_subscription_level_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..676442c81f85e8b02828839006afe8096926553e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import ManagementLockListResult +from ._models_py3 import ManagementLockObject + +from ._management_lock_client_enums import LockLevel +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLockListResult", + "ManagementLockObject", + "LockLevel", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/_management_lock_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/_management_lock_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..ef20a9304ed6ef548f4d969499f29f1ea0249564 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/_management_lock_client_enums.py @@ -0,0 +1,18 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class LockLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The lock level of the management lock.""" + + NOT_SPECIFIED = "NotSpecified" + CAN_NOT_DELETE = "CanNotDelete" + READ_ONLY = "ReadOnly" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..8b016d48f71608ebce85590a29feda955216023a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/_models_py3.py @@ -0,0 +1,104 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class ManagementLockListResult(_serialization.Model): + """List of management locks. + + :ivar value: The list of locks. + :vartype value: list[~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject] + :ivar next_link: The URL to get the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ManagementLockObject]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.ManagementLockObject"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: The list of locks. + :paramtype value: list[~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject] + :keyword next_link: The URL to get the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ManagementLockObject(_serialization.Model): + """Management lock information. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The Id of the lock. + :vartype id: str + :ivar type: The type of the lock. + :vartype type: str + :ivar name: The name of the lock. + :vartype name: str + :ivar level: The lock level of the management lock. Known values are: "NotSpecified", + "CanNotDelete", and "ReadOnly". + :vartype level: str or ~azure.mgmt.resource.locks.v2015_01_01.models.LockLevel + :ivar notes: The notes of the management lock. + :vartype notes: str + """ + + _validation = { + "id": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "level": {"key": "properties.level", "type": "str"}, + "notes": {"key": "properties.notes", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + level: Optional[Union[str, "_models.LockLevel"]] = None, + notes: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of the lock. + :paramtype name: str + :keyword level: The lock level of the management lock. Known values are: "NotSpecified", + "CanNotDelete", and "ReadOnly". + :paramtype level: str or ~azure.mgmt.resource.locks.v2015_01_01.models.LockLevel + :keyword notes: The notes of the management lock. + :paramtype notes: str + """ + super().__init__(**kwargs) + self.id = None + self.type = None + self.name = name + self.level = level + self.notes = notes diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5fe90f3f763822a16947ec6c08efb625640deea1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import ManagementLocksOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLocksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..2e4b7a0f3d5a0794e9b3eb78bf64510ca8b31246 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/operations/_operations.py @@ -0,0 +1,1488 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_management_locks_create_or_update_at_resource_group_level_request( + resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_delete_at_resource_group_level_request( + resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_locks_get_at_resource_group_level_request( + resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_create_or_update_at_resource_level_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_delete_at_resource_level_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_locks_create_or_update_at_subscription_level_request( + lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + ) + path_format_arguments = { + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_delete_at_subscription_level_request( + lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + ) + path_format_arguments = { + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_locks_get_request(lock_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + ) + path_format_arguments = { + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_list_at_resource_group_level_request( + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_list_at_resource_level_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_list_at_subscription_level_request( + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ManagementLocksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.locks.v2015_01_01.ManagementLockClient`'s + :attr:`management_locks` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource group level. + + :param resource_group_name: The resource group name. Required. + :type resource_group_name: str + :param lock_name: The lock name. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource group level. + + :param resource_group_name: The resource group name. Required. + :type resource_group_name: str + :param lock_name: The lock name. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource group level. + + :param resource_group_name: The resource group name. Required. + :type resource_group_name: str + :param lock_name: The lock name. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def delete_at_resource_group_level( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lock_name: str, **kwargs: Any + ) -> None: + """Deletes the management lock of a resource group. + + :param resource_group_name: The resource group name. Required. + :type resource_group_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def get_at_resource_group_level( + self, resource_group_name: str, lock_name: str, **kwargs: Any + ) -> _models.ManagementLockObject: + """Gets a management lock at the resource group level. + + :param resource_group_name: The resource group name. Required. + :type resource_group_name: str + :param lock_name: The lock name. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @overload + def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource level or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: Resource identity. Required. + :type resource_provider_namespace: str + :param parent_resource_path: Resource identity. Required. + :type parent_resource_path: str + :param resource_type: Resource identity. Required. + :type resource_type: str + :param resource_name: Resource identity. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource level or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: Resource identity. Required. + :type resource_provider_namespace: str + :param parent_resource_path: Resource identity. Required. + :type parent_resource_path: str + :param resource_type: Resource identity. Required. + :type resource_type: str + :param resource_name: Resource identity. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the resource level or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: Resource identity. Required. + :type resource_provider_namespace: str + :param parent_resource_path: Resource identity. Required. + :type parent_resource_path: str + :param resource_type: Resource identity. Required. + :type resource_type: str + :param resource_name: Resource identity. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Is either a + ManagementLockObject type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def delete_at_resource_level( # pylint: disable=inconsistent-return-statements + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + **kwargs: Any + ) -> None: + """Deletes the management lock of a resource or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: Resource identity. Required. + :type resource_provider_namespace: str + :param parent_resource_path: Resource identity. Required. + :type parent_resource_path: str + :param resource_type: Resource identity. Required. + :type resource_type: str + :param resource_name: Resource identity. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @overload + def create_or_update_at_subscription_level( + self, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the subscription level. + + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_subscription_level( + self, lock_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the subscription level. + + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_subscription_level( + self, lock_name: str, parameters: Union[_models.ManagementLockObject, IO], **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock at the subscription level. + + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def delete_at_subscription_level( # pylint: disable=inconsistent-return-statements + self, lock_name: str, **kwargs: Any + ) -> None: + """Deletes the management lock of a subscription. + + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def get(self, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: + """Gets the management lock of a scope. + + :param lock_name: Name of the management lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}"} + + @distributed_trace + def list_at_resource_group_level( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.ManagementLockObject"]: + """Gets all the management locks of a resource group. + + :param resource_group_name: Resource group name. Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_resource_group_level_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks" + } + + @distributed_trace + def list_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.ManagementLockObject"]: + """Gets all the management locks of a resource or any level below resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param resource_provider_namespace: Resource identity. Required. + :type resource_provider_namespace: str + :param parent_resource_path: Resource identity. Required. + :type parent_resource_path: str + :param resource_type: Resource identity. Required. + :type resource_type: str + :param resource_name: Resource identity. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks" + } + + @distributed_trace + def list_at_subscription_level( + self, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.ManagementLockObject"]: + """Gets all the management locks of a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.v2015_01_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-01-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_subscription_level_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2015_01_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4a02cc9246e62a7d7f8d2f7ff8738564f4095768 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._management_lock_client import ManagementLockClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLockClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..d2a5da467cfa217902656aed440ab001392b767b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class ManagementLockClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ManagementLockClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ManagementLockClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", "2016-09-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_management_lock_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_management_lock_client.py new file mode 100644 index 0000000000000000000000000000000000000000..2490a8f247c7fd0b5b620bae1d53c3822c395b99 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_management_lock_client.py @@ -0,0 +1,99 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import ManagementLockClientConfiguration +from .operations import AuthorizationOperationsOperations, ManagementLocksOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class ManagementLockClient: # pylint: disable=client-accepts-api-version-keyword + """Azure resources can be locked to prevent other users in your organization from deleting or + modifying resources. + + :ivar authorization_operations: AuthorizationOperationsOperations operations + :vartype authorization_operations: + azure.mgmt.resource.locks.v2016_09_01.operations.AuthorizationOperationsOperations + :ivar management_locks: ManagementLocksOperations operations + :vartype management_locks: + azure.mgmt.resource.locks.v2016_09_01.operations.ManagementLocksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ManagementLockClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.authorization_operations = AuthorizationOperationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.management_locks = ManagementLocksOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "ManagementLockClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0df84f5319f2e522d0fec4553e2e8b04bf904a --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_vendor.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import List, cast + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..38ced0793f4166879d6ef8932a3e97f0cf1f3239 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "23.0.1" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..021d914862b0be2ef39c0d904d834b5b68b7a490 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._management_lock_client import ManagementLockClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLockClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..32fc153c90b645025da02ea88bac7e3444751afa --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementLockClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ManagementLockClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ManagementLockClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", "2016-09-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/_management_lock_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/_management_lock_client.py new file mode 100644 index 0000000000000000000000000000000000000000..f968ad082615f8cf63e8873bdc5438aa13144893 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/_management_lock_client.py @@ -0,0 +1,99 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import ManagementLockClientConfiguration +from .operations import AuthorizationOperationsOperations, ManagementLocksOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagementLockClient: # pylint: disable=client-accepts-api-version-keyword + """Azure resources can be locked to prevent other users in your organization from deleting or + modifying resources. + + :ivar authorization_operations: AuthorizationOperationsOperations operations + :vartype authorization_operations: + azure.mgmt.resource.locks.v2016_09_01.aio.operations.AuthorizationOperationsOperations + :ivar management_locks: ManagementLocksOperations operations + :vartype management_locks: + azure.mgmt.resource.locks.v2016_09_01.aio.operations.ManagementLocksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2016-09-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ManagementLockClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.authorization_operations = AuthorizationOperationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.management_locks = ManagementLocksOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "ManagementLockClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3f16a5cf4b0887afd4b3be2a2673bf8c5e5aa42c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import AuthorizationOperationsOperations +from ._operations import ManagementLocksOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AuthorizationOperationsOperations", + "ManagementLocksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..bf8caf7bdfddfab3c00d58c28f45be9d699a1ffe --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/operations/_operations.py @@ -0,0 +1,1742 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_authorization_operations_list_request, + build_management_locks_create_or_update_at_resource_group_level_request, + build_management_locks_create_or_update_at_resource_level_request, + build_management_locks_create_or_update_at_subscription_level_request, + build_management_locks_create_or_update_by_scope_request, + build_management_locks_delete_at_resource_group_level_request, + build_management_locks_delete_at_resource_level_request, + build_management_locks_delete_at_subscription_level_request, + build_management_locks_delete_by_scope_request, + build_management_locks_get_at_resource_group_level_request, + build_management_locks_get_at_resource_level_request, + build_management_locks_get_at_subscription_level_request, + build_management_locks_get_by_scope_request, + build_management_locks_list_at_resource_group_level_request, + build_management_locks_list_at_resource_level_request, + build_management_locks_list_at_subscription_level_request, + build_management_locks_list_by_scope_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AuthorizationOperationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.locks.v2016_09_01.aio.ManagementLockClient`'s + :attr:`authorization_operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + """Lists all of the available Microsoft.Authorization REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.v2016_09_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_authorization_operations_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} + + +class ManagementLocksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.locks.v2016_09_01.aio.ManagementLockClient`'s + :attr:`management_locks` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace_async + async def delete_at_resource_group_level( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lock_name: str, **kwargs: Any + ) -> None: + """Deletes a management lock at the resource group level. + + To delete management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the lock. Required. + :type resource_group_name: str + :param lock_name: The name of lock to delete. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace_async + async def get_at_resource_group_level( + self, resource_group_name: str, lock_name: str, **kwargs: Any + ) -> _models.ManagementLockObject: + """Gets a management lock at the resource group level. + + :param resource_group_name: The name of the locked resource group. Required. + :type resource_group_name: str + :param lock_name: The name of the lock to get. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @overload + async def create_or_update_by_scope( + self, + scope: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_by_scope( + self, scope: str, lock_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_by_scope( + self, scope: str, lock_name: str, parameters: Union[_models.ManagementLockObject, IO], **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Is either a + ManagementLockObject type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/locks/{lockName}"} + + @distributed_trace_async + async def delete_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, lock_name: str, **kwargs: Any + ) -> None: + """Delete a management lock by scope. + + :param scope: The scope for the lock. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + template_url=self.delete_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/locks/{lockName}"} + + @distributed_trace_async + async def get_by_scope(self, scope: str, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: + """Get a management lock by scope. + + :param scope: The scope for the lock. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + template_url=self.get_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/locks/{lockName}"} + + @overload + async def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Is either a + ManagementLockObject type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace_async + async def delete_at_resource_level( # pylint: disable=inconsistent-return-statements + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + **kwargs: Any + ) -> None: + """Deletes the management lock of a resource or any level below the resource. + + To delete management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource with the + lock to delete. Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource with the + lock to delete. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource with the lock to delete. Required. + :type resource_type: str + :param resource_name: The name of the resource with the lock to delete. Required. + :type resource_name: str + :param lock_name: The name of the lock to delete. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace_async + async def get_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + **kwargs: Any + ) -> _models.ManagementLockObject: + """Get the management lock of a resource or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: An extra path parameter needed in some services, like SQL + Databases. Required. + :type parent_resource_path: str + :param resource_type: The type of the resource. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @overload + async def create_or_update_at_subscription_level( + self, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_subscription_level( + self, lock_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_subscription_level( + self, lock_name: str, parameters: Union[_models.ManagementLockObject, IO], **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace_async + async def delete_at_subscription_level( # pylint: disable=inconsistent-return-statements + self, lock_name: str, **kwargs: Any + ) -> None: + """Deletes the management lock at the subscription level. + + To delete management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock to delete. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace_async + async def get_at_subscription_level(self, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: + """Gets a management lock at the subscription level. + + :param lock_name: The name of the lock to get. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def list_at_resource_group_level( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ManagementLockObject"]: + """Gets all the management locks for a resource group. + + :param resource_group_name: The name of the resource group containing the locks to get. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_resource_group_level_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks" + } + + @distributed_trace + def list_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.ManagementLockObject"]: + """Gets all the management locks for a resource or any level below resource. + + :param resource_group_name: The name of the resource group containing the locked resource. The + name is case insensitive. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the locked resource. Required. + :type resource_type: str + :param resource_name: The name of the locked resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks" + } + + @distributed_trace + def list_at_subscription_level( + self, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ManagementLockObject"]: + """Gets all the management locks for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_subscription_level_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks" + } + + @distributed_trace + def list_by_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ManagementLockObject"]: + """Gets all the management locks for a scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_by_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/locks"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c31f16caec29bc2d24ead6ee0e7092d2f61c73b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/__init__.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import ManagementLockListResult +from ._models_py3 import ManagementLockObject +from ._models_py3 import ManagementLockOwner +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult + +from ._management_lock_client_enums import LockLevel +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ManagementLockListResult", + "ManagementLockObject", + "ManagementLockOwner", + "Operation", + "OperationDisplay", + "OperationListResult", + "LockLevel", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/_management_lock_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/_management_lock_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..672293de07fe1458b43c3d4f2cc8698354d15961 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/_management_lock_client_enums.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class LockLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete + means authorized users are able to read and modify the resources, but not delete. ReadOnly + means authorized users can only read from a resource, but they can't modify or delete it. + """ + + NOT_SPECIFIED = "NotSpecified" + CAN_NOT_DELETE = "CanNotDelete" + READ_ONLY = "ReadOnly" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..4eec71e7633bdf13f911253fe362c66ec7bc546f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/_models_py3.py @@ -0,0 +1,233 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class ManagementLockListResult(_serialization.Model): + """The list of locks. + + :ivar value: The list of locks. + :vartype value: list[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ManagementLockObject]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.ManagementLockObject"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: The list of locks. + :paramtype value: list[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ManagementLockObject(_serialization.Model): + """The lock information. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The resource ID of the lock. + :vartype id: str + :ivar type: The resource type of the lock - Microsoft.Authorization/locks. + :vartype type: str + :ivar name: The name of the lock. + :vartype name: str + :ivar level: The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. + CanNotDelete means authorized users are able to read and modify the resources, but not delete. + ReadOnly means authorized users can only read from a resource, but they can't modify or delete + it. Required. Known values are: "NotSpecified", "CanNotDelete", and "ReadOnly". + :vartype level: str or ~azure.mgmt.resource.locks.v2016_09_01.models.LockLevel + :ivar notes: Notes about the lock. Maximum of 512 characters. + :vartype notes: str + :ivar owners: The owners of the lock. + :vartype owners: list[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockOwner] + """ + + _validation = { + "id": {"readonly": True}, + "type": {"readonly": True}, + "name": {"readonly": True}, + "level": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "level": {"key": "properties.level", "type": "str"}, + "notes": {"key": "properties.notes", "type": "str"}, + "owners": {"key": "properties.owners", "type": "[ManagementLockOwner]"}, + } + + def __init__( + self, + *, + level: Union[str, "_models.LockLevel"], + notes: Optional[str] = None, + owners: Optional[List["_models.ManagementLockOwner"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword level: The level of the lock. Possible values are: NotSpecified, CanNotDelete, + ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but + not delete. ReadOnly means authorized users can only read from a resource, but they can't + modify or delete it. Required. Known values are: "NotSpecified", "CanNotDelete", and + "ReadOnly". + :paramtype level: str or ~azure.mgmt.resource.locks.v2016_09_01.models.LockLevel + :keyword notes: Notes about the lock. Maximum of 512 characters. + :paramtype notes: str + :keyword owners: The owners of the lock. + :paramtype owners: list[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockOwner] + """ + super().__init__(**kwargs) + self.id = None + self.type = None + self.name = None + self.level = level + self.notes = notes + self.owners = owners + + +class ManagementLockOwner(_serialization.Model): + """Lock owner properties. + + :ivar application_id: The application ID of the lock owner. + :vartype application_id: str + """ + + _attribute_map = { + "application_id": {"key": "applicationId", "type": "str"}, + } + + def __init__(self, *, application_id: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword application_id: The application ID of the lock owner. + :paramtype application_id: str + """ + super().__init__(**kwargs) + self.application_id = application_id + + +class Operation(_serialization.Model): + """Microsoft.Authorization operation. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.resource.locks.v2016_09_01.models.OperationDisplay + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + } + + def __init__( + self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any + ) -> None: + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: The object that represents the operation. + :paramtype display: ~azure.mgmt.resource.locks.v2016_09_01.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = name + self.display = display + + +class OperationDisplay(_serialization.Model): + """The object that represents the operation. + + :ivar provider: Service provider: Microsoft.Authorization. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Profile, endpoint, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + """ + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Service provider: Microsoft.Authorization. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed: Profile, endpoint, etc. + :paramtype resource: str + :keyword operation: Operation type: Read, write, delete, etc. + :paramtype operation: str + """ + super().__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + + +class OperationListResult(_serialization.Model): + """Result of the request to list Microsoft.Authorization operations. It contains a list of + operations and a URL link to get the next set of results. + + :ivar value: List of Microsoft.Authorization operations. + :vartype value: list[~azure.mgmt.resource.locks.v2016_09_01.models.Operation] + :ivar next_link: URL to get the next set of operation list results if there are any. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: List of Microsoft.Authorization operations. + :paramtype value: list[~azure.mgmt.resource.locks.v2016_09_01.models.Operation] + :keyword next_link: URL to get the next set of operation list results if there are any. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3f16a5cf4b0887afd4b3be2a2673bf8c5e5aa42c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import AuthorizationOperationsOperations +from ._operations import ManagementLocksOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AuthorizationOperationsOperations", + "ManagementLocksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..ba15dddf1d919f7af566f34832f531d6ff4aee0e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/operations/_operations.py @@ -0,0 +1,2261 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_authorization_operations_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_create_or_update_at_resource_group_level_request( + resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_delete_at_resource_group_level_request( + resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_locks_get_at_resource_group_level_request( + resource_group_name: str, lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_create_or_update_by_scope_request(scope: str, lock_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks/{lockName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_delete_by_scope_request(scope: str, lock_name: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks/{lockName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_locks_get_by_scope_request(scope: str, lock_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks/{lockName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_create_or_update_at_resource_level_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_delete_at_resource_level_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_locks_get_at_resource_level_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_create_or_update_at_subscription_level_request( + lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + ) + path_format_arguments = { + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_delete_at_subscription_level_request( + lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + ) + path_format_arguments = { + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_management_locks_get_at_subscription_level_request( + lock_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + ) + path_format_arguments = { + "lockName": _SERIALIZER.url("lock_name", lock_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_list_at_resource_group_level_request( + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_list_at_resource_level_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_list_at_subscription_level_request( + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_management_locks_list_by_scope_request( + scope: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Authorization/locks") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AuthorizationOperationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.locks.v2016_09_01.ManagementLockClient`'s + :attr:`authorization_operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: + """Lists all of the available Microsoft.Authorization REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.v2016_09_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_authorization_operations_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Authorization/operations"} + + +class ManagementLocksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.locks.v2016_09_01.ManagementLockClient`'s + :attr:`management_locks` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_resource_group_level( + self, + resource_group_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource group level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group to lock. Required. + :type resource_group_name: str + :param lock_name: The lock name. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def delete_at_resource_group_level( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lock_name: str, **kwargs: Any + ) -> None: + """Deletes a management lock at the resource group level. + + To delete management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the lock. Required. + :type resource_group_name: str + :param lock_name: The name of lock to delete. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def get_at_resource_group_level( + self, resource_group_name: str, lock_name: str, **kwargs: Any + ) -> _models.ManagementLockObject: + """Gets a management lock at the resource group level. + + :param resource_group_name: The name of the locked resource group. Required. + :type resource_group_name: str + :param lock_name: The name of the lock to get. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_at_resource_group_level_request( + resource_group_name=resource_group_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @overload + def create_or_update_by_scope( + self, + scope: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_by_scope( + self, scope: str, lock_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_by_scope( + self, scope: str, lock_name: str, parameters: Union[_models.ManagementLockObject, IO], **kwargs: Any + ) -> _models.ManagementLockObject: + """Create or update a management lock by scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :param parameters: Create or update management lock parameters. Is either a + ManagementLockObject type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/locks/{lockName}"} + + @distributed_trace + def delete_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, lock_name: str, **kwargs: Any + ) -> None: + """Delete a management lock by scope. + + :param scope: The scope for the lock. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + template_url=self.delete_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/locks/{lockName}"} + + @distributed_trace + def get_by_scope(self, scope: str, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: + """Get a management lock by scope. + + :param scope: The scope for the lock. Required. + :type scope: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_by_scope_request( + scope=scope, + lock_name=lock_name, + api_version=api_version, + template_url=self.get_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/locks/{lockName}"} + + @overload + def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + parameters: Union[_models.ManagementLockObject, IO], + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the resource level or any level below the resource. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource to lock. + Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource to lock. + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource to lock. Required. + :type resource_type: str + :param resource_name: The name of the resource to lock. Required. + :type resource_name: str + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: Parameters for creating or updating a management lock. Is either a + ManagementLockObject type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def delete_at_resource_level( # pylint: disable=inconsistent-return-statements + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + **kwargs: Any + ) -> None: + """Deletes the management lock of a resource or any level below the resource. + + To delete management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param resource_group_name: The name of the resource group containing the resource with the + lock to delete. Required. + :type resource_group_name: str + :param resource_provider_namespace: The resource provider namespace of the resource with the + lock to delete. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the resource with the lock to delete. Required. + :type resource_type: str + :param resource_name: The name of the resource with the lock to delete. Required. + :type resource_name: str + :param lock_name: The name of the lock to delete. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def get_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + lock_name: str, + **kwargs: Any + ) -> _models.ManagementLockObject: + """Get the management lock of a resource or any level below resource. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: An extra path parameter needed in some services, like SQL + Databases. Required. + :type parent_resource_path: str + :param resource_type: The type of the resource. Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param lock_name: The name of lock. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @overload + def create_or_update_at_subscription_level( + self, + lock_name: str, + parameters: _models.ManagementLockObject, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_subscription_level( + self, lock_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_subscription_level( + self, lock_name: str, parameters: Union[_models.ManagementLockObject, IO], **kwargs: Any + ) -> _models.ManagementLockObject: + """Creates or updates a management lock at the subscription level. + + When you apply a lock at a parent scope, all child resources inherit the same lock. To create + management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock. The lock name can be a maximum of 260 characters. It cannot + contain <, > %, &, :, \, ?, /, or any control characters. Required. + :type lock_name: str + :param parameters: The management lock parameters. Is either a ManagementLockObject type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ManagementLockObject") + + request = build_management_locks_create_or_update_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def delete_at_subscription_level( # pylint: disable=inconsistent-return-statements + self, lock_name: str, **kwargs: Any + ) -> None: + """Deletes the management lock at the subscription level. + + To delete management locks, you must have access to Microsoft.Authorization/\ * or + Microsoft.Authorization/locks/* actions. Of the built-in roles, only Owner and User Access + Administrator are granted those actions. + + :param lock_name: The name of lock to delete. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_management_locks_delete_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def get_at_subscription_level(self, lock_name: str, **kwargs: Any) -> _models.ManagementLockObject: + """Gets a management lock at the subscription level. + + :param lock_name: The name of the lock to get. Required. + :type lock_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ManagementLockObject or the result of cls(response) + :rtype: ~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockObject] = kwargs.pop("cls", None) + + request = build_management_locks_get_at_subscription_level_request( + lock_name=lock_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ManagementLockObject", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks/{lockName}" + } + + @distributed_trace + def list_at_resource_group_level( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.ManagementLockObject"]: + """Gets all the management locks for a resource group. + + :param resource_group_name: The name of the resource group containing the locks to get. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_resource_group_level_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_resource_group_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_at_resource_group_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/locks" + } + + @distributed_trace + def list_at_resource_level( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.ManagementLockObject"]: + """Gets all the management locks for a resource or any level below resource. + + :param resource_group_name: The name of the resource group containing the locked resource. The + name is case insensitive. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource identity. Required. + :type parent_resource_path: str + :param resource_type: The resource type of the locked resource. Required. + :type resource_type: str + :param resource_name: The name of the locked resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_resource_level_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_resource_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_at_resource_level.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/locks" + } + + @distributed_trace + def list_at_subscription_level( + self, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.ManagementLockObject"]: + """Gets all the management locks for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_at_subscription_level_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_at_subscription_level.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_at_subscription_level.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/locks" + } + + @distributed_trace + def list_by_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.ManagementLockObject"]: + """Gets all the management locks for a scope. + + :param scope: The scope for the lock. When providing a scope for the assignment, use + '/subscriptions/{subscriptionId}' for subscriptions, + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and + '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' + for resources. Required. + :type scope: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ManagementLockObject or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.locks.v2016_09_01.models.ManagementLockObject] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-09-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + cls: ClsType[_models.ManagementLockListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_management_locks_list_by_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ManagementLockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/locks"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/locks/v2016_09_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..42ac8700d5dffe9d37b913090754e324d2568698 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._application_client import ApplicationClient +__all__ = ['ApplicationClient'] diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/_application_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/_application_client.py new file mode 100644 index 0000000000000000000000000000000000000000..f678f4c1e128e47a1aafd20234512dc8bdda596f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/_application_client.py @@ -0,0 +1,145 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.mgmt.core import AsyncARMPipelineClient +from azure.profiles import KnownProfiles, ProfileDefinition +from azure.profiles.multiapiclient import MultiApiClientMixin + +from .._serialization import Deserializer, Serializer +from ._configuration import ApplicationClientConfiguration +from ._operations_mixin import ApplicationClientOperationsMixin + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class _SDKClient(object): + def __init__(self, *args, **kwargs): + """This is a fake class to support current implemetation of MultiApiClientMixin." + Will be removed in final version of multiapi azure-core based client + """ + pass + +class ApplicationClient(ApplicationClientOperationsMixin, MultiApiClientMixin, _SDKClient): + """ARM applications. + + This ready contains multiple API versions, to help you deal with all of the Azure clouds + (Azure Stack, Azure Government, Azure China, etc.). + By default, it uses the latest API version available on public Azure. + For production, you should stick to a particular api-version and/or profile. + The profile sets a mapping between an operation group and its API version. + The api-version parameter sets the default API version if the operation + group is not described in the profile. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param api_version: API version to use if no profile is provided, or if missing in profile. + :type api_version: str + :param base_url: Service URL + :type base_url: str + :param profile: A profile definition, from KnownProfiles to dict. + :type profile: azure.profiles.KnownProfiles + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + DEFAULT_API_VERSION = '2019-07-01' + _PROFILE_TAG = "azure.mgmt.resource.managedapplications.ApplicationClient" + LATEST_PROFILE = ProfileDefinition({ + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + }}, + _PROFILE_TAG + " latest" + ) + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + api_version: Optional[str] = None, + base_url: str = "https://management.azure.com", + profile: KnownProfiles = KnownProfiles.default, + **kwargs: Any + ) -> None: + self._config = ApplicationClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + super(ApplicationClient, self).__init__( + api_version=api_version, + profile=profile + ) + + @classmethod + def _models_dict(cls, api_version): + return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} + + @classmethod + def models(cls, api_version=DEFAULT_API_VERSION): + """Module depends on the API version: + + * 2019-07-01: :mod:`v2019_07_01.models` + """ + if api_version == '2019-07-01': + from ..v2019_07_01 import models + return models + raise ValueError("API version {} is not available".format(api_version)) + + @property + def application_definitions(self): + """Instance depends on the API version: + + * 2019-07-01: :class:`ApplicationDefinitionsOperations` + """ + api_version = self._get_api_version('application_definitions') + if api_version == '2019-07-01': + from ..v2019_07_01.aio.operations import ApplicationDefinitionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'application_definitions'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def applications(self): + """Instance depends on the API version: + + * 2019-07-01: :class:`ApplicationsOperations` + """ + api_version = self._get_api_version('applications') + if api_version == '2019-07-01': + from ..v2019_07_01.aio.operations import ApplicationsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'applications'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def jit_requests(self): + """Instance depends on the API version: + + * 2019-07-01: :class:`JitRequestsOperations` + """ + api_version = self._get_api_version('jit_requests') + if api_version == '2019-07-01': + from ..v2019_07_01.aio.operations import JitRequestsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'jit_requests'".format(api_version)) + self._config.api_version = api_version + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + async def close(self): + await self._client.close() + async def __aenter__(self): + await self._client.__aenter__() + return self + async def __aexit__(self, *exc_details): + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..d428af1a3d4f96301860a52c9da2b86215602e87 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +class ApplicationClientConfiguration(Configuration): + """Configuration for ApplicationClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(ApplicationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'azure-mgmt-resource/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/_operations_mixin.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/_operations_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..ee76b5b74bf87f861793b91975c06816a8ad7eca --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/aio/_operations_mixin.py @@ -0,0 +1,45 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from .._serialization import Serializer, Deserializer +from typing import Any, AsyncIterable + +from azure.core.async_paging import AsyncItemPaged + +from .. import models as _models + + +class ApplicationClientOperationsMixin(object): + + def list_operations( + self, + **kwargs: Any + ) -> AsyncIterable["_models.Operation"]: + """Lists all of the available Microsoft.Solutions REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + api_version = self._get_api_version('list_operations') + if api_version == '2019-07-01': + from ..v2019_07_01.aio.operations import ApplicationClientOperationsMixin as OperationClass + else: + raise ValueError("API version {} does not have operation 'list_operations'".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._config.api_version = api_version + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._serialize.client_side_validation = False + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return mixin_instance.list_operations(**kwargs) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e5d22f85da86163d71cdbcf78d2df97beca7b855 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._application_client import ApplicationClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ApplicationClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_application_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_application_client.py new file mode 100644 index 0000000000000000000000000000000000000000..1588ebf62a8f6564f97ac1a35b744c9f44839d53 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_application_client.py @@ -0,0 +1,105 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import ApplicationClientConfiguration +from .operations import ( + ApplicationClientOperationsMixin, + ApplicationDefinitionsOperations, + ApplicationsOperations, + JitRequestsOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class ApplicationClient(ApplicationClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """ARM applications. + + :ivar applications: ApplicationsOperations operations + :vartype applications: + azure.mgmt.resource.managedapplications.v2019_07_01.operations.ApplicationsOperations + :ivar application_definitions: ApplicationDefinitionsOperations operations + :vartype application_definitions: + azure.mgmt.resource.managedapplications.v2019_07_01.operations.ApplicationDefinitionsOperations + :ivar jit_requests: JitRequestsOperations operations + :vartype jit_requests: + azure.mgmt.resource.managedapplications.v2019_07_01.operations.JitRequestsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ApplicationClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.applications = ApplicationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.application_definitions = ApplicationDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.jit_requests = JitRequestsOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "ApplicationClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..50052d1bfef809f5342863d4f5b092a73e9ecfb4 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class ApplicationClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ApplicationClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ApplicationClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", "2019-07-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..06217a584f6385d0aabdccc463f9933424dee32e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_vendor.py @@ -0,0 +1,48 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import List, TYPE_CHECKING, cast + +from azure.core.pipeline.transport import HttpRequest + +from ._configuration import ApplicationClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core import PipelineClient + + from .._serialization import Deserializer, Serializer + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) + + +class ApplicationClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "PipelineClient" + _config: ApplicationClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..38ced0793f4166879d6ef8932a3e97f0cf1f3239 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "23.0.1" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f3eee99c42a5adf9db1724f67ac5b72ce53d856f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._application_client import ApplicationClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ApplicationClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_application_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_application_client.py new file mode 100644 index 0000000000000000000000000000000000000000..274f188a182120eb6251ecee09fa67904c075601 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_application_client.py @@ -0,0 +1,105 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import ApplicationClientConfiguration +from .operations import ( + ApplicationClientOperationsMixin, + ApplicationDefinitionsOperations, + ApplicationsOperations, + JitRequestsOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class ApplicationClient(ApplicationClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """ARM applications. + + :ivar applications: ApplicationsOperations operations + :vartype applications: + azure.mgmt.resource.managedapplications.v2019_07_01.aio.operations.ApplicationsOperations + :ivar application_definitions: ApplicationDefinitionsOperations operations + :vartype application_definitions: + azure.mgmt.resource.managedapplications.v2019_07_01.aio.operations.ApplicationDefinitionsOperations + :ivar jit_requests: JitRequestsOperations operations + :vartype jit_requests: + azure.mgmt.resource.managedapplications.v2019_07_01.aio.operations.JitRequestsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ApplicationClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.applications = ApplicationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.application_definitions = ApplicationDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.jit_requests = JitRequestsOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "ApplicationClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..f902df95544f88b861bd6e5621438361a57748dc --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class ApplicationClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ApplicationClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2019-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ApplicationClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", "2019-07-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_vendor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..e1c36555e3a260970d9861fc7d9ee3533984402f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/_vendor.py @@ -0,0 +1,28 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import TYPE_CHECKING + +from azure.core.pipeline.transport import HttpRequest + +from ._configuration import ApplicationClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core import AsyncPipelineClient + + from ..._serialization import Deserializer, Serializer + + +class ApplicationClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "AsyncPipelineClient" + _config: ApplicationClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8eb99a2dc9453cb8db10e5ff0241f6954d06b6c7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import ApplicationClientOperationsMixin +from ._operations import ApplicationsOperations +from ._operations import ApplicationDefinitionsOperations +from ._operations import JitRequestsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ApplicationClientOperationsMixin", + "ApplicationsOperations", + "ApplicationDefinitionsOperations", + "JitRequestsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..38aec5fbd9863cc993d20a914d8dc50a93283a3b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/operations/_operations.py @@ -0,0 +1,3095 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_application_definitions_create_or_update_by_id_request, + build_application_definitions_create_or_update_request, + build_application_definitions_delete_by_id_request, + build_application_definitions_delete_request, + build_application_definitions_get_by_id_request, + build_application_definitions_get_request, + build_application_definitions_list_by_resource_group_request, + build_application_list_operations_request, + build_applications_create_or_update_by_id_request, + build_applications_create_or_update_request, + build_applications_delete_by_id_request, + build_applications_delete_request, + build_applications_get_by_id_request, + build_applications_get_request, + build_applications_list_by_resource_group_request, + build_applications_list_by_subscription_request, + build_applications_refresh_permissions_request, + build_applications_update_by_id_request, + build_applications_update_request, + build_jit_requests_create_or_update_request, + build_jit_requests_delete_request, + build_jit_requests_get_request, + build_jit_requests_list_by_resource_group_request, + build_jit_requests_list_by_subscription_request, + build_jit_requests_update_request, +) +from .._vendor import ApplicationClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ApplicationClientOperationsMixin(ApplicationClientMixinABC): + @distributed_trace + def list_operations(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + """Lists all of the available Microsoft.Solutions REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_application_list_operations_request( + api_version=api_version, + template_url=self.list_operations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_operations.metadata = {"url": "/providers/Microsoft.Solutions/operations"} + + +class ApplicationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.v2019_07_01.aio.ApplicationClient`'s + :attr:`applications` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, resource_group_name: str, application_name: str, **kwargs: Any) -> _models.Application: + """Gets the managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + request = build_applications_get_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_applications_delete_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + application_name=application_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + async def _create_or_update_initial( + self, resource_group_name: str, application_name: str, parameters: Union[_models.Application, IO], **kwargs: Any + ) -> _models.Application: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Application") + + request = build_applications_create_or_update_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("Application", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + application_name: str, + parameters: _models.Application, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + application_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, resource_group_name: str, application_name: str, parameters: Union[_models.Application, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Is either + a Application type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + application_name=application_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Application", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + @overload + async def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[_models.ApplicationPatchable] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPatchable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[IO] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[Union[_models.ApplicationPatchable, IO]] = None, + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Is either a + ApplicationPatchable type or a IO type. Default value is None. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPatchable or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.Application]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + if parameters is not None: + _json = self._serialize.body(parameters, "ApplicationPatchable") + else: + _json = None + + request = build_applications_update_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Application"]: + """Gets all the applications within a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Application or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_applications_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications" + } + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Application"]: + """Gets all the applications within a subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Application or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_applications_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_subscription.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Solutions/applications" + } + + @distributed_trace_async + async def get_by_id(self, application_id: str, **kwargs: Any) -> _models.Application: + """Gets the managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + request = build_applications_get_by_id_request( + application_id=application_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{applicationId}"} + + async def _delete_by_id_initial( # pylint: disable=inconsistent-return-statements + self, application_id: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_applications_delete_by_id_request( + application_id=application_id, + api_version=api_version, + template_url=self._delete_by_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_by_id_initial.metadata = {"url": "/{applicationId}"} + + @distributed_trace_async + async def begin_delete_by_id(self, application_id: str, **kwargs: Any) -> AsyncLROPoller[None]: + """Deletes the managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_by_id_initial( # type: ignore + application_id=application_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete_by_id.metadata = {"url": "/{applicationId}"} + + async def _create_or_update_by_id_initial( + self, application_id: str, parameters: Union[_models.Application, IO], **kwargs: Any + ) -> _models.Application: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Application") + + request = build_applications_create_or_update_by_id_request( + application_id=application_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_by_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("Application", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_by_id_initial.metadata = {"url": "/{applicationId}"} + + @overload + async def begin_create_or_update_by_id( + self, + application_id: str, + parameters: _models.Application, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update_by_id( + self, application_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update_by_id( + self, application_id: str, parameters: Union[_models.Application, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Is either + a Application type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_by_id_initial( + application_id=application_id, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Application", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update_by_id.metadata = {"url": "/{applicationId}"} + + @overload + async def update_by_id( + self, + application_id: str, + parameters: Optional[_models.Application] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_by_id( + self, + application_id: str, + parameters: Optional[IO] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update_by_id( + self, application_id: str, parameters: Optional[Union[_models.Application, IO]] = None, **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Is either a + Application type or a IO type. Default value is None. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + if parameters is not None: + _json = self._serialize.body(parameters, "Application") + else: + _json = None + + request = build_applications_update_by_id_request( + application_id=application_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update_by_id.metadata = {"url": "/{applicationId}"} + + async def _refresh_permissions_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_applications_refresh_permissions_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._refresh_permissions_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _refresh_permissions_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}/refreshPermissions" + } + + @distributed_trace_async + async def begin_refresh_permissions( + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Refresh Permissions for application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._refresh_permissions_initial( # type: ignore + resource_group_name=resource_group_name, + application_name=application_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_refresh_permissions.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}/refreshPermissions" + } + + +class ApplicationDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.v2019_07_01.aio.ApplicationClient`'s + :attr:`application_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> _models.ApplicationDefinition: + """Gets the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ApplicationDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + request = build_application_definitions_get_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_application_definitions_delete_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition to delete. + Required. + :type application_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + async def _create_or_update_initial( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO], + **kwargs: Any + ) -> _models.ApplicationDefinition: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ApplicationDefinition") + + request = build_application_definitions_create_or_update_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: _models.ApplicationDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Is either a ApplicationDefinition type or a IO type. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ApplicationDefinition"]: + """Lists the managed application definitions in a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.ApplicationDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_application_definitions_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions" + } + + @distributed_trace_async + async def get_by_id( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> _models.ApplicationDefinition: + """Gets the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ApplicationDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + request = build_application_definitions_get_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + async def _delete_by_id_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_application_definitions_delete_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_by_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_by_id_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + @distributed_trace_async + async def begin_delete_by_id( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_by_id_initial( # type: ignore + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete_by_id.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + async def _create_or_update_by_id_initial( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO], + **kwargs: Any + ) -> _models.ApplicationDefinition: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ApplicationDefinition") + + request = build_application_definitions_create_or_update_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_by_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_by_id_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + @overload + async def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: _models.ApplicationDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Is either a ApplicationDefinition type or a IO type. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ApplicationDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_by_id_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update_by_id.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + +class JitRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.v2019_07_01.aio.ApplicationClient`'s + :attr:`jit_requests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, resource_group_name: str, jit_request_name: str, **kwargs: Any) -> _models.JitRequestDefinition: + """Gets the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + + request = build_jit_requests_get_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}" + } + + async def _create_or_update_initial( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestDefinition, IO], + **kwargs: Any + ) -> _models.JitRequestDefinition: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "JitRequestDefinition") + + request = build_jit_requests_create_or_update_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("JitRequestDefinition", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("JitRequestDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: _models.JitRequestDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either JitRequestDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either JitRequestDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestDefinition, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Is either a + JitRequestDefinition type or a IO type. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either JitRequestDefinition or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("JitRequestDefinition", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}" + } + + @overload + async def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: _models.JitRequestPatchable, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestPatchable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestPatchable, IO], + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Is either a + JitRequestPatchable type or a IO type. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestPatchable or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "JitRequestPatchable") + + request = build_jit_requests_update_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}" + } + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, jit_request_name: str, **kwargs: Any + ) -> None: + """Deletes the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_jit_requests_delete_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}" + } + + @distributed_trace_async + async def list_by_subscription(self, **kwargs: Any) -> _models.JitRequestDefinitionListResult: + """Retrieves all JIT requests within the subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinitionListResult or the result of cls(response) + :rtype: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinitionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) + + request = build_jit_requests_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Solutions/jitRequests"} + + @distributed_trace_async + async def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> _models.JitRequestDefinitionListResult: + """Retrieves all JIT requests within the resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinitionListResult or the result of cls(response) + :rtype: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinitionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) + + request = build_jit_requests_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b139d32504dce058bca915beb07ffc597e173e2 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/__init__.py @@ -0,0 +1,127 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import Application +from ._models_py3 import ApplicationArtifact +from ._models_py3 import ApplicationAuthorization +from ._models_py3 import ApplicationBillingDetailsDefinition +from ._models_py3 import ApplicationClientDetails +from ._models_py3 import ApplicationDefinition +from ._models_py3 import ApplicationDefinitionArtifact +from ._models_py3 import ApplicationDefinitionListResult +from ._models_py3 import ApplicationDeploymentPolicy +from ._models_py3 import ApplicationJitAccessPolicy +from ._models_py3 import ApplicationListResult +from ._models_py3 import ApplicationManagementPolicy +from ._models_py3 import ApplicationNotificationEndpoint +from ._models_py3 import ApplicationNotificationPolicy +from ._models_py3 import ApplicationPackageContact +from ._models_py3 import ApplicationPackageLockingPolicyDefinition +from ._models_py3 import ApplicationPackageSupportUrls +from ._models_py3 import ApplicationPatchable +from ._models_py3 import ApplicationPolicy +from ._models_py3 import ApplicationPropertiesPatchable +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import GenericResource +from ._models_py3 import Identity +from ._models_py3 import JitApproverDefinition +from ._models_py3 import JitAuthorizationPolicies +from ._models_py3 import JitRequestDefinition +from ._models_py3 import JitRequestDefinitionListResult +from ._models_py3 import JitRequestPatchable +from ._models_py3 import JitSchedulingPolicy +from ._models_py3 import Operation +from ._models_py3 import OperationAutoGenerated +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationDisplayAutoGenerated +from ._models_py3 import OperationListResult +from ._models_py3 import Plan +from ._models_py3 import PlanPatchable +from ._models_py3 import Resource +from ._models_py3 import Sku +from ._models_py3 import UserAssignedResourceIdentity + +from ._application_client_enums import ActionType +from ._application_client_enums import ApplicationArtifactName +from ._application_client_enums import ApplicationArtifactType +from ._application_client_enums import ApplicationDefinitionArtifactName +from ._application_client_enums import ApplicationLockLevel +from ._application_client_enums import ApplicationManagementMode +from ._application_client_enums import DeploymentMode +from ._application_client_enums import JitApprovalMode +from ._application_client_enums import JitApproverType +from ._application_client_enums import JitRequestState +from ._application_client_enums import JitSchedulingType +from ._application_client_enums import Origin +from ._application_client_enums import ProvisioningState +from ._application_client_enums import ResourceIdentityType +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Application", + "ApplicationArtifact", + "ApplicationAuthorization", + "ApplicationBillingDetailsDefinition", + "ApplicationClientDetails", + "ApplicationDefinition", + "ApplicationDefinitionArtifact", + "ApplicationDefinitionListResult", + "ApplicationDeploymentPolicy", + "ApplicationJitAccessPolicy", + "ApplicationListResult", + "ApplicationManagementPolicy", + "ApplicationNotificationEndpoint", + "ApplicationNotificationPolicy", + "ApplicationPackageContact", + "ApplicationPackageLockingPolicyDefinition", + "ApplicationPackageSupportUrls", + "ApplicationPatchable", + "ApplicationPolicy", + "ApplicationPropertiesPatchable", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "GenericResource", + "Identity", + "JitApproverDefinition", + "JitAuthorizationPolicies", + "JitRequestDefinition", + "JitRequestDefinitionListResult", + "JitRequestPatchable", + "JitSchedulingPolicy", + "Operation", + "OperationAutoGenerated", + "OperationDisplay", + "OperationDisplayAutoGenerated", + "OperationListResult", + "Plan", + "PlanPatchable", + "Resource", + "Sku", + "UserAssignedResourceIdentity", + "ActionType", + "ApplicationArtifactName", + "ApplicationArtifactType", + "ApplicationDefinitionArtifactName", + "ApplicationLockLevel", + "ApplicationManagementMode", + "DeploymentMode", + "JitApprovalMode", + "JitApproverType", + "JitRequestState", + "JitSchedulingType", + "Origin", + "ProvisioningState", + "ResourceIdentityType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/_application_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/_application_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..ce93a089dad3e59bda35182de468d36fd383e5af --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/_application_client_enums.py @@ -0,0 +1,138 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.""" + + INTERNAL = "Internal" + + +class ApplicationArtifactName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The managed application artifact name.""" + + NOT_SPECIFIED = "NotSpecified" + VIEW_DEFINITION = "ViewDefinition" + AUTHORIZATIONS = "Authorizations" + CUSTOM_ROLE_DEFINITION = "CustomRoleDefinition" + + +class ApplicationArtifactType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The managed application artifact type.""" + + NOT_SPECIFIED = "NotSpecified" + TEMPLATE = "Template" + CUSTOM = "Custom" + + +class ApplicationDefinitionArtifactName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The managed application artifact name.""" + + NOT_SPECIFIED = "NotSpecified" + APPLICATION_RESOURCE_TEMPLATE = "ApplicationResourceTemplate" + CREATE_UI_DEFINITION = "CreateUiDefinition" + MAIN_TEMPLATE_PARAMETERS = "MainTemplateParameters" + + +class ApplicationLockLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The managed application lock level.""" + + CAN_NOT_DELETE = "CanNotDelete" + READ_ONLY = "ReadOnly" + NONE = "None" + + +class ApplicationManagementMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The management mode.""" + + NOT_SPECIFIED = "NotSpecified" + UNMANAGED = "Unmanaged" + MANAGED = "Managed" + + +class DeploymentMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The deployment mode.""" + + NOT_SPECIFIED = "NotSpecified" + INCREMENTAL = "Incremental" + COMPLETE = "Complete" + + +class JitApprovalMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The Jit approval mode.""" + + NOT_SPECIFIED = "NotSpecified" + AUTO_APPROVE = "AutoApprove" + MANUAL_APPROVE = "ManualApprove" + + +class JitApproverType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The approver type.""" + + USER = "user" + GROUP = "group" + + +class JitRequestState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The JIT request state.""" + + NOT_SPECIFIED = "NotSpecified" + PENDING = "Pending" + APPROVED = "Approved" + DENIED = "Denied" + FAILED = "Failed" + CANCELED = "Canceled" + EXPIRED = "Expired" + TIMEOUT = "Timeout" + + +class JitSchedulingType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The JIT request scheduling type.""" + + NOT_SPECIFIED = "NotSpecified" + ONCE = "Once" + RECURRING = "Recurring" + + +class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit + logs UX. Default value is "user,system". + """ + + USER = "user" + SYSTEM = "system" + USER_SYSTEM = "user,system" + + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Provisioning status of the managed application.""" + + NOT_SPECIFIED = "NotSpecified" + ACCEPTED = "Accepted" + RUNNING = "Running" + READY = "Ready" + CREATING = "Creating" + CREATED = "Created" + DELETING = "Deleting" + DELETED = "Deleted" + CANCELED = "Canceled" + FAILED = "Failed" + SUCCEEDED = "Succeeded" + UPDATING = "Updating" + + +class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type.""" + + SYSTEM_ASSIGNED = "SystemAssigned" + USER_ASSIGNED = "UserAssigned" + SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned, UserAssigned" + NONE = "None" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..5df73c993f084b275a7098cb1bd378a061e71f37 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/_models_py3.py @@ -0,0 +1,2177 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +import sys +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + + +class Resource(_serialization.Model): + """Resource information. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, *, location: Optional[str] = None, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.location = location + self.tags = tags + + +class GenericResource(Resource): + """Resource information. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar managed_by: ID of the resource that manages this resource. + :vartype managed_by: str + :ivar sku: The SKU of the resource. + :vartype sku: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Sku + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "managed_by": {"key": "managedBy", "type": "str"}, + "sku": {"key": "sku", "type": "Sku"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + managed_by: Optional[str] = None, + sku: Optional["_models.Sku"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword managed_by: ID of the resource that manages this resource. + :paramtype managed_by: str + :keyword sku: The SKU of the resource. + :paramtype sku: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Sku + """ + super().__init__(location=location, tags=tags, **kwargs) + self.managed_by = managed_by + self.sku = sku + + +class Application(GenericResource): # pylint: disable=too-many-instance-attributes + """Information about managed application. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar managed_by: ID of the resource that manages this resource. + :vartype managed_by: str + :ivar sku: The SKU of the resource. + :vartype sku: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Sku + :ivar plan: The plan information. + :vartype plan: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Plan + :ivar kind: The kind of the managed application. Allowed values are MarketPlace and + ServiceCatalog. Required. + :vartype kind: str + :ivar identity: The identity of the resource. + :vartype identity: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Identity + :ivar managed_resource_group_id: The managed resource group Id. + :vartype managed_resource_group_id: str + :ivar application_definition_id: The fully qualified path of managed application definition Id. + :vartype application_definition_id: str + :ivar parameters: Name and value pairs that define the managed application parameters. It can + be a JObject or a well formed JSON string. + :vartype parameters: JSON + :ivar outputs: Name and value pairs that define the managed application outputs. + :vartype outputs: JSON + :ivar provisioning_state: The managed application provisioning state. Known values are: + "NotSpecified", "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", + "Canceled", "Failed", "Succeeded", and "Updating". + :vartype provisioning_state: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ProvisioningState + :ivar billing_details: The managed application billing details. + :vartype billing_details: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationBillingDetailsDefinition + :ivar jit_access_policy: The managed application Jit access policy. + :vartype jit_access_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationJitAccessPolicy + :ivar publisher_tenant_id: The publisher tenant Id. + :vartype publisher_tenant_id: str + :ivar authorizations: The read-only authorizations property that is retrieved from the + application package. + :vartype authorizations: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationAuthorization] + :ivar management_mode: The managed application management mode. Known values are: + "NotSpecified", "Unmanaged", and "Managed". + :vartype management_mode: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationManagementMode + :ivar customer_support: The read-only customer support property that is retrieved from the + application package. + :vartype customer_support: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPackageContact + :ivar support_urls: The read-only support URLs property that is retrieved from the application + package. + :vartype support_urls: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPackageSupportUrls + :ivar artifacts: The collection of managed application artifacts. + :vartype artifacts: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationArtifact] + :ivar created_by: The client entity that created the JIT request. + :vartype created_by: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationClientDetails + :ivar updated_by: The client entity that last updated the JIT request. + :vartype updated_by: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationClientDetails + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "kind": {"required": True, "pattern": r"^[-\w\._,\(\)]+$"}, + "outputs": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "billing_details": {"readonly": True}, + "publisher_tenant_id": {"readonly": True}, + "authorizations": {"readonly": True}, + "management_mode": {"readonly": True}, + "customer_support": {"readonly": True}, + "support_urls": {"readonly": True}, + "artifacts": {"readonly": True}, + "created_by": {"readonly": True}, + "updated_by": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "managed_by": {"key": "managedBy", "type": "str"}, + "sku": {"key": "sku", "type": "Sku"}, + "plan": {"key": "plan", "type": "Plan"}, + "kind": {"key": "kind", "type": "str"}, + "identity": {"key": "identity", "type": "Identity"}, + "managed_resource_group_id": {"key": "properties.managedResourceGroupId", "type": "str"}, + "application_definition_id": {"key": "properties.applicationDefinitionId", "type": "str"}, + "parameters": {"key": "properties.parameters", "type": "object"}, + "outputs": {"key": "properties.outputs", "type": "object"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "billing_details": {"key": "properties.billingDetails", "type": "ApplicationBillingDetailsDefinition"}, + "jit_access_policy": {"key": "properties.jitAccessPolicy", "type": "ApplicationJitAccessPolicy"}, + "publisher_tenant_id": {"key": "properties.publisherTenantId", "type": "str"}, + "authorizations": {"key": "properties.authorizations", "type": "[ApplicationAuthorization]"}, + "management_mode": {"key": "properties.managementMode", "type": "str"}, + "customer_support": {"key": "properties.customerSupport", "type": "ApplicationPackageContact"}, + "support_urls": {"key": "properties.supportUrls", "type": "ApplicationPackageSupportUrls"}, + "artifacts": {"key": "properties.artifacts", "type": "[ApplicationArtifact]"}, + "created_by": {"key": "properties.createdBy", "type": "ApplicationClientDetails"}, + "updated_by": {"key": "properties.updatedBy", "type": "ApplicationClientDetails"}, + } + + def __init__( # pylint: disable=too-many-locals + self, + *, + kind: str, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + managed_by: Optional[str] = None, + sku: Optional["_models.Sku"] = None, + plan: Optional["_models.Plan"] = None, + identity: Optional["_models.Identity"] = None, + managed_resource_group_id: Optional[str] = None, + application_definition_id: Optional[str] = None, + parameters: Optional[JSON] = None, + jit_access_policy: Optional["_models.ApplicationJitAccessPolicy"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword managed_by: ID of the resource that manages this resource. + :paramtype managed_by: str + :keyword sku: The SKU of the resource. + :paramtype sku: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Sku + :keyword plan: The plan information. + :paramtype plan: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Plan + :keyword kind: The kind of the managed application. Allowed values are MarketPlace and + ServiceCatalog. Required. + :paramtype kind: str + :keyword identity: The identity of the resource. + :paramtype identity: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Identity + :keyword managed_resource_group_id: The managed resource group Id. + :paramtype managed_resource_group_id: str + :keyword application_definition_id: The fully qualified path of managed application definition + Id. + :paramtype application_definition_id: str + :keyword parameters: Name and value pairs that define the managed application parameters. It + can be a JObject or a well formed JSON string. + :paramtype parameters: JSON + :keyword jit_access_policy: The managed application Jit access policy. + :paramtype jit_access_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationJitAccessPolicy + """ + super().__init__(location=location, tags=tags, managed_by=managed_by, sku=sku, **kwargs) + self.plan = plan + self.kind = kind + self.identity = identity + self.managed_resource_group_id = managed_resource_group_id + self.application_definition_id = application_definition_id + self.parameters = parameters + self.outputs = None + self.provisioning_state = None + self.billing_details = None + self.jit_access_policy = jit_access_policy + self.publisher_tenant_id = None + self.authorizations = None + self.management_mode = None + self.customer_support = None + self.support_urls = None + self.artifacts = None + self.created_by = None + self.updated_by = None + + +class ApplicationArtifact(_serialization.Model): + """Managed application artifact. + + All required parameters must be populated in order to send to Azure. + + :ivar name: The managed application artifact name. Required. Known values are: "NotSpecified", + "ViewDefinition", "Authorizations", and "CustomRoleDefinition". + :vartype name: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationArtifactName + :ivar uri: The managed application artifact blob uri. Required. + :vartype uri: str + :ivar type: The managed application artifact type. Required. Known values are: "NotSpecified", + "Template", and "Custom". + :vartype type: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationArtifactType + """ + + _validation = { + "name": {"required": True}, + "uri": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "uri": {"key": "uri", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + name: Union[str, "_models.ApplicationArtifactName"], + uri: str, + type: Union[str, "_models.ApplicationArtifactType"], + **kwargs: Any + ) -> None: + """ + :keyword name: The managed application artifact name. Required. Known values are: + "NotSpecified", "ViewDefinition", "Authorizations", and "CustomRoleDefinition". + :paramtype name: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationArtifactName + :keyword uri: The managed application artifact blob uri. Required. + :paramtype uri: str + :keyword type: The managed application artifact type. Required. Known values are: + "NotSpecified", "Template", and "Custom". + :paramtype type: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationArtifactType + """ + super().__init__(**kwargs) + self.name = name + self.uri = uri + self.type = type + + +class ApplicationAuthorization(_serialization.Model): + """The managed application provider authorization. + + All required parameters must be populated in order to send to Azure. + + :ivar principal_id: The provider's principal identifier. This is the identity that the provider + will use to call ARM to manage the managed application resources. Required. + :vartype principal_id: str + :ivar role_definition_id: The provider's role definition identifier. This role will define all + the permissions that the provider must have on the managed application's container resource + group. This role definition cannot have permission to delete the resource group. Required. + :vartype role_definition_id: str + """ + + _validation = { + "principal_id": {"required": True}, + "role_definition_id": {"required": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + } + + def __init__(self, *, principal_id: str, role_definition_id: str, **kwargs: Any) -> None: + """ + :keyword principal_id: The provider's principal identifier. This is the identity that the + provider will use to call ARM to manage the managed application resources. Required. + :paramtype principal_id: str + :keyword role_definition_id: The provider's role definition identifier. This role will define + all the permissions that the provider must have on the managed application's container resource + group. This role definition cannot have permission to delete the resource group. Required. + :paramtype role_definition_id: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.role_definition_id = role_definition_id + + +class ApplicationBillingDetailsDefinition(_serialization.Model): + """Managed application billing details definition. + + :ivar resource_usage_id: The managed application resource usage Id. + :vartype resource_usage_id: str + """ + + _attribute_map = { + "resource_usage_id": {"key": "resourceUsageId", "type": "str"}, + } + + def __init__(self, *, resource_usage_id: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword resource_usage_id: The managed application resource usage Id. + :paramtype resource_usage_id: str + """ + super().__init__(**kwargs) + self.resource_usage_id = resource_usage_id + + +class ApplicationClientDetails(_serialization.Model): + """The application client details to track the entity creating/updating the managed app resource. + + :ivar oid: The client Oid. + :vartype oid: str + :ivar puid: The client Puid. + :vartype puid: str + :ivar application_id: The client application Id. + :vartype application_id: str + """ + + _attribute_map = { + "oid": {"key": "oid", "type": "str"}, + "puid": {"key": "puid", "type": "str"}, + "application_id": {"key": "applicationId", "type": "str"}, + } + + def __init__( + self, + *, + oid: Optional[str] = None, + puid: Optional[str] = None, + application_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword oid: The client Oid. + :paramtype oid: str + :keyword puid: The client Puid. + :paramtype puid: str + :keyword application_id: The client application Id. + :paramtype application_id: str + """ + super().__init__(**kwargs) + self.oid = oid + self.puid = puid + self.application_id = application_id + + +class ApplicationDefinition(GenericResource): # pylint: disable=too-many-instance-attributes + """Information about managed application definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar managed_by: ID of the resource that manages this resource. + :vartype managed_by: str + :ivar sku: The SKU of the resource. + :vartype sku: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Sku + :ivar lock_level: The managed application lock level. Required. Known values are: + "CanNotDelete", "ReadOnly", and "None". + :vartype lock_level: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationLockLevel + :ivar display_name: The managed application definition display name. + :vartype display_name: str + :ivar is_enabled: A value indicating whether the package is enabled or not. + :vartype is_enabled: bool + :ivar authorizations: The managed application provider authorizations. + :vartype authorizations: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationAuthorization] + :ivar artifacts: The collection of managed application artifacts. The portal will use the files + specified as artifacts to construct the user experience of creating a managed application from + a managed application definition. + :vartype artifacts: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinitionArtifact] + :ivar description: The managed application definition description. + :vartype description: str + :ivar package_file_uri: The managed application definition package file Uri. Use this element. + :vartype package_file_uri: str + :ivar main_template: The inline main template json which has resources to be provisioned. It + can be a JObject or well-formed JSON string. + :vartype main_template: JSON + :ivar create_ui_definition: The createUiDefinition json for the backing template with + Microsoft.Solutions/applications resource. It can be a JObject or well-formed JSON string. + :vartype create_ui_definition: JSON + :ivar notification_policy: The managed application notification policy. + :vartype notification_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationNotificationPolicy + :ivar locking_policy: The managed application locking policy. + :vartype locking_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPackageLockingPolicyDefinition + :ivar deployment_policy: The managed application deployment policy. + :vartype deployment_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDeploymentPolicy + :ivar management_policy: The managed application management policy that determines publisher's + access to the managed resource group. + :vartype management_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationManagementPolicy + :ivar policies: The managed application provider policies. + :vartype policies: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPolicy] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "lock_level": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "managed_by": {"key": "managedBy", "type": "str"}, + "sku": {"key": "sku", "type": "Sku"}, + "lock_level": {"key": "properties.lockLevel", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "is_enabled": {"key": "properties.isEnabled", "type": "bool"}, + "authorizations": {"key": "properties.authorizations", "type": "[ApplicationAuthorization]"}, + "artifacts": {"key": "properties.artifacts", "type": "[ApplicationDefinitionArtifact]"}, + "description": {"key": "properties.description", "type": "str"}, + "package_file_uri": {"key": "properties.packageFileUri", "type": "str"}, + "main_template": {"key": "properties.mainTemplate", "type": "object"}, + "create_ui_definition": {"key": "properties.createUiDefinition", "type": "object"}, + "notification_policy": {"key": "properties.notificationPolicy", "type": "ApplicationNotificationPolicy"}, + "locking_policy": {"key": "properties.lockingPolicy", "type": "ApplicationPackageLockingPolicyDefinition"}, + "deployment_policy": {"key": "properties.deploymentPolicy", "type": "ApplicationDeploymentPolicy"}, + "management_policy": {"key": "properties.managementPolicy", "type": "ApplicationManagementPolicy"}, + "policies": {"key": "properties.policies", "type": "[ApplicationPolicy]"}, + } + + def __init__( + self, + *, + lock_level: Union[str, "_models.ApplicationLockLevel"], + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + managed_by: Optional[str] = None, + sku: Optional["_models.Sku"] = None, + display_name: Optional[str] = None, + is_enabled: Optional[bool] = None, + authorizations: Optional[List["_models.ApplicationAuthorization"]] = None, + artifacts: Optional[List["_models.ApplicationDefinitionArtifact"]] = None, + description: Optional[str] = None, + package_file_uri: Optional[str] = None, + main_template: Optional[JSON] = None, + create_ui_definition: Optional[JSON] = None, + notification_policy: Optional["_models.ApplicationNotificationPolicy"] = None, + locking_policy: Optional["_models.ApplicationPackageLockingPolicyDefinition"] = None, + deployment_policy: Optional["_models.ApplicationDeploymentPolicy"] = None, + management_policy: Optional["_models.ApplicationManagementPolicy"] = None, + policies: Optional[List["_models.ApplicationPolicy"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword managed_by: ID of the resource that manages this resource. + :paramtype managed_by: str + :keyword sku: The SKU of the resource. + :paramtype sku: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Sku + :keyword lock_level: The managed application lock level. Required. Known values are: + "CanNotDelete", "ReadOnly", and "None". + :paramtype lock_level: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationLockLevel + :keyword display_name: The managed application definition display name. + :paramtype display_name: str + :keyword is_enabled: A value indicating whether the package is enabled or not. + :paramtype is_enabled: bool + :keyword authorizations: The managed application provider authorizations. + :paramtype authorizations: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationAuthorization] + :keyword artifacts: The collection of managed application artifacts. The portal will use the + files specified as artifacts to construct the user experience of creating a managed application + from a managed application definition. + :paramtype artifacts: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinitionArtifact] + :keyword description: The managed application definition description. + :paramtype description: str + :keyword package_file_uri: The managed application definition package file Uri. Use this + element. + :paramtype package_file_uri: str + :keyword main_template: The inline main template json which has resources to be provisioned. It + can be a JObject or well-formed JSON string. + :paramtype main_template: JSON + :keyword create_ui_definition: The createUiDefinition json for the backing template with + Microsoft.Solutions/applications resource. It can be a JObject or well-formed JSON string. + :paramtype create_ui_definition: JSON + :keyword notification_policy: The managed application notification policy. + :paramtype notification_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationNotificationPolicy + :keyword locking_policy: The managed application locking policy. + :paramtype locking_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPackageLockingPolicyDefinition + :keyword deployment_policy: The managed application deployment policy. + :paramtype deployment_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDeploymentPolicy + :keyword management_policy: The managed application management policy that determines + publisher's access to the managed resource group. + :paramtype management_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationManagementPolicy + :keyword policies: The managed application provider policies. + :paramtype policies: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPolicy] + """ + super().__init__(location=location, tags=tags, managed_by=managed_by, sku=sku, **kwargs) + self.lock_level = lock_level + self.display_name = display_name + self.is_enabled = is_enabled + self.authorizations = authorizations + self.artifacts = artifacts + self.description = description + self.package_file_uri = package_file_uri + self.main_template = main_template + self.create_ui_definition = create_ui_definition + self.notification_policy = notification_policy + self.locking_policy = locking_policy + self.deployment_policy = deployment_policy + self.management_policy = management_policy + self.policies = policies + + +class ApplicationDefinitionArtifact(_serialization.Model): + """Application definition artifact. + + All required parameters must be populated in order to send to Azure. + + :ivar name: The managed application definition artifact name. Required. Known values are: + "NotSpecified", "ApplicationResourceTemplate", "CreateUiDefinition", and + "MainTemplateParameters". + :vartype name: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinitionArtifactName + :ivar uri: The managed application definition artifact blob uri. Required. + :vartype uri: str + :ivar type: The managed application definition artifact type. Required. Known values are: + "NotSpecified", "Template", and "Custom". + :vartype type: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationArtifactType + """ + + _validation = { + "name": {"required": True}, + "uri": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "uri": {"key": "uri", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + name: Union[str, "_models.ApplicationDefinitionArtifactName"], + uri: str, + type: Union[str, "_models.ApplicationArtifactType"], + **kwargs: Any + ) -> None: + """ + :keyword name: The managed application definition artifact name. Required. Known values are: + "NotSpecified", "ApplicationResourceTemplate", "CreateUiDefinition", and + "MainTemplateParameters". + :paramtype name: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinitionArtifactName + :keyword uri: The managed application definition artifact blob uri. Required. + :paramtype uri: str + :keyword type: The managed application definition artifact type. Required. Known values are: + "NotSpecified", "Template", and "Custom". + :paramtype type: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationArtifactType + """ + super().__init__(**kwargs) + self.name = name + self.uri = uri + self.type = type + + +class ApplicationDefinitionListResult(_serialization.Model): + """List of managed application definitions. + + :ivar value: The array of managed application definitions. + :vartype value: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ApplicationDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.ApplicationDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: The array of managed application definitions. + :paramtype value: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ApplicationDeploymentPolicy(_serialization.Model): + """Managed application deployment policy. + + All required parameters must be populated in order to send to Azure. + + :ivar deployment_mode: The managed application deployment mode. Required. Known values are: + "NotSpecified", "Incremental", and "Complete". + :vartype deployment_mode: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.DeploymentMode + """ + + _validation = { + "deployment_mode": {"required": True}, + } + + _attribute_map = { + "deployment_mode": {"key": "deploymentMode", "type": "str"}, + } + + def __init__(self, *, deployment_mode: Union[str, "_models.DeploymentMode"], **kwargs: Any) -> None: + """ + :keyword deployment_mode: The managed application deployment mode. Required. Known values are: + "NotSpecified", "Incremental", and "Complete". + :paramtype deployment_mode: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.DeploymentMode + """ + super().__init__(**kwargs) + self.deployment_mode = deployment_mode + + +class ApplicationJitAccessPolicy(_serialization.Model): + """Managed application Jit access policy. + + All required parameters must be populated in order to send to Azure. + + :ivar jit_access_enabled: Whether the JIT access is enabled. Required. + :vartype jit_access_enabled: bool + :ivar jit_approval_mode: JIT approval mode. Known values are: "NotSpecified", "AutoApprove", + and "ManualApprove". + :vartype jit_approval_mode: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitApprovalMode + :ivar jit_approvers: The JIT approvers. + :vartype jit_approvers: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitApproverDefinition] + :ivar maximum_jit_access_duration: The maximum duration JIT access is granted. This is an + ISO8601 time period value. + :vartype maximum_jit_access_duration: str + """ + + _validation = { + "jit_access_enabled": {"required": True}, + } + + _attribute_map = { + "jit_access_enabled": {"key": "jitAccessEnabled", "type": "bool"}, + "jit_approval_mode": {"key": "jitApprovalMode", "type": "str"}, + "jit_approvers": {"key": "jitApprovers", "type": "[JitApproverDefinition]"}, + "maximum_jit_access_duration": {"key": "maximumJitAccessDuration", "type": "str"}, + } + + def __init__( + self, + *, + jit_access_enabled: bool, + jit_approval_mode: Optional[Union[str, "_models.JitApprovalMode"]] = None, + jit_approvers: Optional[List["_models.JitApproverDefinition"]] = None, + maximum_jit_access_duration: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword jit_access_enabled: Whether the JIT access is enabled. Required. + :paramtype jit_access_enabled: bool + :keyword jit_approval_mode: JIT approval mode. Known values are: "NotSpecified", "AutoApprove", + and "ManualApprove". + :paramtype jit_approval_mode: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitApprovalMode + :keyword jit_approvers: The JIT approvers. + :paramtype jit_approvers: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitApproverDefinition] + :keyword maximum_jit_access_duration: The maximum duration JIT access is granted. This is an + ISO8601 time period value. + :paramtype maximum_jit_access_duration: str + """ + super().__init__(**kwargs) + self.jit_access_enabled = jit_access_enabled + self.jit_approval_mode = jit_approval_mode + self.jit_approvers = jit_approvers + self.maximum_jit_access_duration = maximum_jit_access_duration + + +class ApplicationListResult(_serialization.Model): + """List of managed applications. + + :ivar value: The array of managed applications. + :vartype value: list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Application]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.Application"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: The array of managed applications. + :paramtype value: list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ApplicationManagementPolicy(_serialization.Model): + """Managed application management policy. + + :ivar mode: The managed application management mode. Known values are: "NotSpecified", + "Unmanaged", and "Managed". + :vartype mode: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationManagementMode + """ + + _attribute_map = { + "mode": {"key": "mode", "type": "str"}, + } + + def __init__( + self, *, mode: Optional[Union[str, "_models.ApplicationManagementMode"]] = None, **kwargs: Any + ) -> None: + """ + :keyword mode: The managed application management mode. Known values are: "NotSpecified", + "Unmanaged", and "Managed". + :paramtype mode: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationManagementMode + """ + super().__init__(**kwargs) + self.mode = mode + + +class ApplicationNotificationEndpoint(_serialization.Model): + """Managed application notification endpoint. + + All required parameters must be populated in order to send to Azure. + + :ivar uri: The managed application notification endpoint uri. Required. + :vartype uri: str + """ + + _validation = { + "uri": {"required": True}, + } + + _attribute_map = { + "uri": {"key": "uri", "type": "str"}, + } + + def __init__(self, *, uri: str, **kwargs: Any) -> None: + """ + :keyword uri: The managed application notification endpoint uri. Required. + :paramtype uri: str + """ + super().__init__(**kwargs) + self.uri = uri + + +class ApplicationNotificationPolicy(_serialization.Model): + """Managed application notification policy. + + All required parameters must be populated in order to send to Azure. + + :ivar notification_endpoints: The managed application notification endpoint. Required. + :vartype notification_endpoints: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationNotificationEndpoint] + """ + + _validation = { + "notification_endpoints": {"required": True}, + } + + _attribute_map = { + "notification_endpoints": {"key": "notificationEndpoints", "type": "[ApplicationNotificationEndpoint]"}, + } + + def __init__( + self, *, notification_endpoints: List["_models.ApplicationNotificationEndpoint"], **kwargs: Any + ) -> None: + """ + :keyword notification_endpoints: The managed application notification endpoint. Required. + :paramtype notification_endpoints: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationNotificationEndpoint] + """ + super().__init__(**kwargs) + self.notification_endpoints = notification_endpoints + + +class ApplicationPackageContact(_serialization.Model): + """The application package contact information. + + All required parameters must be populated in order to send to Azure. + + :ivar contact_name: The contact name. + :vartype contact_name: str + :ivar email: The contact email. Required. + :vartype email: str + :ivar phone: The contact phone number. Required. + :vartype phone: str + """ + + _validation = { + "email": {"required": True}, + "phone": {"required": True}, + } + + _attribute_map = { + "contact_name": {"key": "contactName", "type": "str"}, + "email": {"key": "email", "type": "str"}, + "phone": {"key": "phone", "type": "str"}, + } + + def __init__(self, *, email: str, phone: str, contact_name: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword contact_name: The contact name. + :paramtype contact_name: str + :keyword email: The contact email. Required. + :paramtype email: str + :keyword phone: The contact phone number. Required. + :paramtype phone: str + """ + super().__init__(**kwargs) + self.contact_name = contact_name + self.email = email + self.phone = phone + + +class ApplicationPackageLockingPolicyDefinition(_serialization.Model): + """Managed application locking policy. + + :ivar allowed_actions: The deny assignment excluded actions. + :vartype allowed_actions: list[str] + :ivar allowed_data_actions: The deny assignment excluded data actions. + :vartype allowed_data_actions: list[str] + """ + + _attribute_map = { + "allowed_actions": {"key": "allowedActions", "type": "[str]"}, + "allowed_data_actions": {"key": "allowedDataActions", "type": "[str]"}, + } + + def __init__( + self, + *, + allowed_actions: Optional[List[str]] = None, + allowed_data_actions: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword allowed_actions: The deny assignment excluded actions. + :paramtype allowed_actions: list[str] + :keyword allowed_data_actions: The deny assignment excluded data actions. + :paramtype allowed_data_actions: list[str] + """ + super().__init__(**kwargs) + self.allowed_actions = allowed_actions + self.allowed_data_actions = allowed_data_actions + + +class ApplicationPackageSupportUrls(_serialization.Model): + """The appliance package support URLs. + + :ivar public_azure: The public azure support URL. + :vartype public_azure: str + :ivar government_cloud: The government cloud support URL. + :vartype government_cloud: str + """ + + _attribute_map = { + "public_azure": {"key": "publicAzure", "type": "str"}, + "government_cloud": {"key": "governmentCloud", "type": "str"}, + } + + def __init__( + self, *, public_azure: Optional[str] = None, government_cloud: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword public_azure: The public azure support URL. + :paramtype public_azure: str + :keyword government_cloud: The government cloud support URL. + :paramtype government_cloud: str + """ + super().__init__(**kwargs) + self.public_azure = public_azure + self.government_cloud = government_cloud + + +class ApplicationPatchable(GenericResource): # pylint: disable=too-many-instance-attributes + """Information about managed application. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar managed_by: ID of the resource that manages this resource. + :vartype managed_by: str + :ivar sku: The SKU of the resource. + :vartype sku: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Sku + :ivar plan: The plan information. + :vartype plan: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.PlanPatchable + :ivar kind: The kind of the managed application. Allowed values are MarketPlace and + ServiceCatalog. + :vartype kind: str + :ivar identity: The identity of the resource. + :vartype identity: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Identity + :ivar managed_resource_group_id: The managed resource group Id. + :vartype managed_resource_group_id: str + :ivar application_definition_id: The fully qualified path of managed application definition Id. + :vartype application_definition_id: str + :ivar parameters: Name and value pairs that define the managed application parameters. It can + be a JObject or a well formed JSON string. + :vartype parameters: JSON + :ivar outputs: Name and value pairs that define the managed application outputs. + :vartype outputs: JSON + :ivar provisioning_state: The managed application provisioning state. Known values are: + "NotSpecified", "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", + "Canceled", "Failed", "Succeeded", and "Updating". + :vartype provisioning_state: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ProvisioningState + :ivar billing_details: The managed application billing details. + :vartype billing_details: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationBillingDetailsDefinition + :ivar jit_access_policy: The managed application Jit access policy. + :vartype jit_access_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationJitAccessPolicy + :ivar publisher_tenant_id: The publisher tenant Id. + :vartype publisher_tenant_id: str + :ivar authorizations: The read-only authorizations property that is retrieved from the + application package. + :vartype authorizations: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationAuthorization] + :ivar management_mode: The managed application management mode. Known values are: + "NotSpecified", "Unmanaged", and "Managed". + :vartype management_mode: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationManagementMode + :ivar customer_support: The read-only customer support property that is retrieved from the + application package. + :vartype customer_support: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPackageContact + :ivar support_urls: The read-only support URLs property that is retrieved from the application + package. + :vartype support_urls: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPackageSupportUrls + :ivar artifacts: The collection of managed application artifacts. + :vartype artifacts: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationArtifact] + :ivar created_by: The client entity that created the JIT request. + :vartype created_by: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationClientDetails + :ivar updated_by: The client entity that last updated the JIT request. + :vartype updated_by: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationClientDetails + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "kind": {"pattern": r"^[-\w\._,\(\)]+$"}, + "outputs": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "billing_details": {"readonly": True}, + "publisher_tenant_id": {"readonly": True}, + "authorizations": {"readonly": True}, + "management_mode": {"readonly": True}, + "customer_support": {"readonly": True}, + "support_urls": {"readonly": True}, + "artifacts": {"readonly": True}, + "created_by": {"readonly": True}, + "updated_by": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "managed_by": {"key": "managedBy", "type": "str"}, + "sku": {"key": "sku", "type": "Sku"}, + "plan": {"key": "plan", "type": "PlanPatchable"}, + "kind": {"key": "kind", "type": "str"}, + "identity": {"key": "identity", "type": "Identity"}, + "managed_resource_group_id": {"key": "properties.managedResourceGroupId", "type": "str"}, + "application_definition_id": {"key": "properties.applicationDefinitionId", "type": "str"}, + "parameters": {"key": "properties.parameters", "type": "object"}, + "outputs": {"key": "properties.outputs", "type": "object"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "billing_details": {"key": "properties.billingDetails", "type": "ApplicationBillingDetailsDefinition"}, + "jit_access_policy": {"key": "properties.jitAccessPolicy", "type": "ApplicationJitAccessPolicy"}, + "publisher_tenant_id": {"key": "properties.publisherTenantId", "type": "str"}, + "authorizations": {"key": "properties.authorizations", "type": "[ApplicationAuthorization]"}, + "management_mode": {"key": "properties.managementMode", "type": "str"}, + "customer_support": {"key": "properties.customerSupport", "type": "ApplicationPackageContact"}, + "support_urls": {"key": "properties.supportUrls", "type": "ApplicationPackageSupportUrls"}, + "artifacts": {"key": "properties.artifacts", "type": "[ApplicationArtifact]"}, + "created_by": {"key": "properties.createdBy", "type": "ApplicationClientDetails"}, + "updated_by": {"key": "properties.updatedBy", "type": "ApplicationClientDetails"}, + } + + def __init__( # pylint: disable=too-many-locals + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + managed_by: Optional[str] = None, + sku: Optional["_models.Sku"] = None, + plan: Optional["_models.PlanPatchable"] = None, + kind: Optional[str] = None, + identity: Optional["_models.Identity"] = None, + managed_resource_group_id: Optional[str] = None, + application_definition_id: Optional[str] = None, + parameters: Optional[JSON] = None, + jit_access_policy: Optional["_models.ApplicationJitAccessPolicy"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword managed_by: ID of the resource that manages this resource. + :paramtype managed_by: str + :keyword sku: The SKU of the resource. + :paramtype sku: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Sku + :keyword plan: The plan information. + :paramtype plan: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.PlanPatchable + :keyword kind: The kind of the managed application. Allowed values are MarketPlace and + ServiceCatalog. + :paramtype kind: str + :keyword identity: The identity of the resource. + :paramtype identity: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Identity + :keyword managed_resource_group_id: The managed resource group Id. + :paramtype managed_resource_group_id: str + :keyword application_definition_id: The fully qualified path of managed application definition + Id. + :paramtype application_definition_id: str + :keyword parameters: Name and value pairs that define the managed application parameters. It + can be a JObject or a well formed JSON string. + :paramtype parameters: JSON + :keyword jit_access_policy: The managed application Jit access policy. + :paramtype jit_access_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationJitAccessPolicy + """ + super().__init__(location=location, tags=tags, managed_by=managed_by, sku=sku, **kwargs) + self.plan = plan + self.kind = kind + self.identity = identity + self.managed_resource_group_id = managed_resource_group_id + self.application_definition_id = application_definition_id + self.parameters = parameters + self.outputs = None + self.provisioning_state = None + self.billing_details = None + self.jit_access_policy = jit_access_policy + self.publisher_tenant_id = None + self.authorizations = None + self.management_mode = None + self.customer_support = None + self.support_urls = None + self.artifacts = None + self.created_by = None + self.updated_by = None + + +class ApplicationPolicy(_serialization.Model): + """Managed application policy. + + :ivar name: The policy name. + :vartype name: str + :ivar policy_definition_id: The policy definition Id. + :vartype policy_definition_id: str + :ivar parameters: The policy parameters. + :vartype parameters: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "policy_definition_id": {"key": "policyDefinitionId", "type": "str"}, + "parameters": {"key": "parameters", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + policy_definition_id: Optional[str] = None, + parameters: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The policy name. + :paramtype name: str + :keyword policy_definition_id: The policy definition Id. + :paramtype policy_definition_id: str + :keyword parameters: The policy parameters. + :paramtype parameters: str + """ + super().__init__(**kwargs) + self.name = name + self.policy_definition_id = policy_definition_id + self.parameters = parameters + + +class ApplicationPropertiesPatchable(_serialization.Model): + """The managed application properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar managed_resource_group_id: The managed resource group Id. + :vartype managed_resource_group_id: str + :ivar application_definition_id: The fully qualified path of managed application definition Id. + :vartype application_definition_id: str + :ivar parameters: Name and value pairs that define the managed application parameters. It can + be a JObject or a well formed JSON string. + :vartype parameters: JSON + :ivar outputs: Name and value pairs that define the managed application outputs. + :vartype outputs: JSON + :ivar provisioning_state: The managed application provisioning state. Known values are: + "NotSpecified", "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", + "Canceled", "Failed", "Succeeded", and "Updating". + :vartype provisioning_state: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ProvisioningState + """ + + _validation = { + "outputs": {"readonly": True}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "managed_resource_group_id": {"key": "managedResourceGroupId", "type": "str"}, + "application_definition_id": {"key": "applicationDefinitionId", "type": "str"}, + "parameters": {"key": "parameters", "type": "object"}, + "outputs": {"key": "outputs", "type": "object"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + } + + def __init__( + self, + *, + managed_resource_group_id: Optional[str] = None, + application_definition_id: Optional[str] = None, + parameters: Optional[JSON] = None, + **kwargs: Any + ) -> None: + """ + :keyword managed_resource_group_id: The managed resource group Id. + :paramtype managed_resource_group_id: str + :keyword application_definition_id: The fully qualified path of managed application definition + Id. + :paramtype application_definition_id: str + :keyword parameters: Name and value pairs that define the managed application parameters. It + can be a JObject or a well formed JSON string. + :paramtype parameters: JSON + """ + super().__init__(**kwargs) + self.managed_resource_group_id = managed_resource_group_id + self.application_definition_id = application_definition_id + self.parameters = parameters + self.outputs = None + self.provisioning_state = None + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class Identity(_serialization.Model): + """Identity for the resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal ID of resource identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of resource. + :vartype tenant_id: str + :ivar type: The identity type. Known values are: "SystemAssigned", "UserAssigned", + "SystemAssigned, UserAssigned", and "None". + :vartype type: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ResourceIdentityType + :ivar user_assigned_identities: The list of user identities associated with the resource. The + user identity dictionary key references will be resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.UserAssignedResourceIdentity] + """ + + _validation = { + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedResourceIdentity}"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.ResourceIdentityType"]] = None, + user_assigned_identities: Optional[Dict[str, "_models.UserAssignedResourceIdentity"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: The identity type. Known values are: "SystemAssigned", "UserAssigned", + "SystemAssigned, UserAssigned", and "None". + :paramtype type: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ResourceIdentityType + :keyword user_assigned_identities: The list of user identities associated with the resource. + The user identity dictionary key references will be resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + :paramtype user_assigned_identities: dict[str, + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.UserAssignedResourceIdentity] + """ + super().__init__(**kwargs) + self.principal_id = None + self.tenant_id = None + self.type = type + self.user_assigned_identities = user_assigned_identities + + +class JitApproverDefinition(_serialization.Model): + """JIT approver definition. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The approver service principal Id. Required. + :vartype id: str + :ivar type: The approver type. Known values are: "user" and "group". + :vartype type: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitApproverType + :ivar display_name: The approver display name. + :vartype display_name: str + """ + + _validation = { + "id": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + type: Optional[Union[str, "_models.JitApproverType"]] = None, + display_name: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The approver service principal Id. Required. + :paramtype id: str + :keyword type: The approver type. Known values are: "user" and "group". + :paramtype type: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitApproverType + :keyword display_name: The approver display name. + :paramtype display_name: str + """ + super().__init__(**kwargs) + self.id = id + self.type = type + self.display_name = display_name + + +class JitAuthorizationPolicies(_serialization.Model): + """The JIT authorization policies. + + All required parameters must be populated in order to send to Azure. + + :ivar principal_id: The the principal id that will be granted JIT access. Required. + :vartype principal_id: str + :ivar role_definition_id: The role definition id that will be granted to the Principal. + Required. + :vartype role_definition_id: str + """ + + _validation = { + "principal_id": {"required": True}, + "role_definition_id": {"required": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "role_definition_id": {"key": "roleDefinitionId", "type": "str"}, + } + + def __init__(self, *, principal_id: str, role_definition_id: str, **kwargs: Any) -> None: + """ + :keyword principal_id: The the principal id that will be granted JIT access. Required. + :paramtype principal_id: str + :keyword role_definition_id: The role definition id that will be granted to the Principal. + Required. + :paramtype role_definition_id: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.role_definition_id = role_definition_id + + +class JitRequestDefinition(Resource): # pylint: disable=too-many-instance-attributes + """Information about JIT request definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource ID. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Resource location. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar application_resource_id: The parent application id. + :vartype application_resource_id: str + :ivar publisher_tenant_id: The publisher tenant id. + :vartype publisher_tenant_id: str + :ivar jit_authorization_policies: The JIT authorization policies. + :vartype jit_authorization_policies: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitAuthorizationPolicies] + :ivar jit_scheduling_policy: The JIT request properties. + :vartype jit_scheduling_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitSchedulingPolicy + :ivar provisioning_state: The JIT request provisioning state. Known values are: "NotSpecified", + "Accepted", "Running", "Ready", "Creating", "Created", "Deleting", "Deleted", "Canceled", + "Failed", "Succeeded", and "Updating". + :vartype provisioning_state: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ProvisioningState + :ivar jit_request_state: The JIT request state. Known values are: "NotSpecified", "Pending", + "Approved", "Denied", "Failed", "Canceled", "Expired", and "Timeout". + :vartype jit_request_state: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestState + :ivar created_by: The client entity that created the JIT request. + :vartype created_by: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationClientDetails + :ivar updated_by: The client entity that last updated the JIT request. + :vartype updated_by: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationClientDetails + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "publisher_tenant_id": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "jit_request_state": {"readonly": True}, + "created_by": {"readonly": True}, + "updated_by": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "application_resource_id": {"key": "properties.applicationResourceId", "type": "str"}, + "publisher_tenant_id": {"key": "properties.publisherTenantId", "type": "str"}, + "jit_authorization_policies": { + "key": "properties.jitAuthorizationPolicies", + "type": "[JitAuthorizationPolicies]", + }, + "jit_scheduling_policy": {"key": "properties.jitSchedulingPolicy", "type": "JitSchedulingPolicy"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "jit_request_state": {"key": "properties.jitRequestState", "type": "str"}, + "created_by": {"key": "properties.createdBy", "type": "ApplicationClientDetails"}, + "updated_by": {"key": "properties.updatedBy", "type": "ApplicationClientDetails"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + application_resource_id: Optional[str] = None, + jit_authorization_policies: Optional[List["_models.JitAuthorizationPolicies"]] = None, + jit_scheduling_policy: Optional["_models.JitSchedulingPolicy"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword application_resource_id: The parent application id. + :paramtype application_resource_id: str + :keyword jit_authorization_policies: The JIT authorization policies. + :paramtype jit_authorization_policies: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitAuthorizationPolicies] + :keyword jit_scheduling_policy: The JIT request properties. + :paramtype jit_scheduling_policy: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitSchedulingPolicy + """ + super().__init__(location=location, tags=tags, **kwargs) + self.application_resource_id = application_resource_id + self.publisher_tenant_id = None + self.jit_authorization_policies = jit_authorization_policies + self.jit_scheduling_policy = jit_scheduling_policy + self.provisioning_state = None + self.jit_request_state = None + self.created_by = None + self.updated_by = None + + +class JitRequestDefinitionListResult(_serialization.Model): + """List of JIT requests. + + :ivar value: The array of Jit request definition. + :vartype value: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[JitRequestDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.JitRequestDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: The array of Jit request definition. + :paramtype value: + list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class JitRequestPatchable(_serialization.Model): + """Information about JIT request. + + :ivar tags: Jit request tags. + :vartype tags: dict[str, str] + """ + + _attribute_map = { + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Jit request tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.tags = tags + + +class JitSchedulingPolicy(_serialization.Model): + """The JIT scheduling policies. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of JIT schedule. Required. Known values are: "NotSpecified", "Once", and + "Recurring". + :vartype type: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitSchedulingType + :ivar duration: The required duration of the JIT request. Required. + :vartype duration: ~datetime.timedelta + :ivar start_time: The start time of the request. Required. + :vartype start_time: ~datetime.datetime + """ + + _validation = { + "type": {"required": True, "readonly": True}, + "duration": {"required": True}, + "start_time": {"required": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "duration": {"key": "duration", "type": "duration"}, + "start_time": {"key": "startTime", "type": "iso-8601"}, + } + + def __init__(self, *, duration: datetime.timedelta, start_time: datetime.datetime, **kwargs: Any) -> None: + """ + :keyword duration: The required duration of the JIT request. Required. + :paramtype duration: ~datetime.timedelta + :keyword start_time: The start time of the request. Required. + :paramtype start_time: ~datetime.datetime + """ + super().__init__(**kwargs) + self.type = None + self.duration = duration + self.start_time = start_time + + +class Operation(_serialization.Model): + """Details of a REST API operation, returned from the Resource Provider Operations API. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + :vartype name: str + :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for + data-plane operations and "false" for ARM/control-plane operations. + :vartype is_data_action: bool + :ivar display: Localized display information for this particular operation. + :vartype display: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.OperationDisplay + :ivar origin: The intended executor of the operation; as in Resource Based Access Control + (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", + and "user,system". + :vartype origin: str or ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Origin + :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for + internal only APIs. "Internal" + :vartype action_type: str or + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ActionType + """ + + _validation = { + "name": {"readonly": True}, + "is_data_action": {"readonly": True}, + "origin": {"readonly": True}, + "action_type": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "action_type": {"key": "actionType", "type": "str"}, + } + + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any) -> None: + """ + :keyword display: Localized display information for this particular operation. + :paramtype display: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = None + self.is_data_action = None + self.display = display + self.origin = None + self.action_type = None + + +class OperationAutoGenerated(_serialization.Model): + """Microsoft.Solutions operation. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.OperationDisplayAutoGenerated + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplayAutoGenerated"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display: Optional["_models.OperationDisplayAutoGenerated"] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: The object that represents the operation. + :paramtype display: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.OperationDisplayAutoGenerated + """ + super().__init__(**kwargs) + self.name = name + self.display = display + + +class OperationDisplay(_serialization.Model): + """Localized display information for this particular operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft + Monitoring Insights" or "Microsoft Compute". + :vartype provider: str + :ivar resource: The localized friendly name of the resource type related to this operation. + E.g. "Virtual Machines" or "Job Schedule Collections". + :vartype resource: str + :ivar operation: The concise, localized friendly name for the operation; suitable for + dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". + :vartype operation: str + :ivar description: The short, localized friendly description of the operation; suitable for + tool tips and detailed views. + :vartype description: str + """ + + _validation = { + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, + } + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationDisplayAutoGenerated(_serialization.Model): + """The object that represents the operation. + + :ivar provider: Service provider: Microsoft.Solutions. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Application, JitRequest, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + """ + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Service provider: Microsoft.Solutions. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed: Application, JitRequest, etc. + :paramtype resource: str + :keyword operation: Operation type: Read, write, delete, etc. + :paramtype operation: str + """ + super().__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + + +class OperationListResult(_serialization.Model): + """A list of REST API operations supported by an Azure Resource Provider. It contains an URL link + to get the next set of results. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of operations supported by the resource provider. + :vartype value: list[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Operation] + :ivar next_link: URL to get the next set of operation list results (if there are any). + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class Plan(_serialization.Model): + """Plan for the managed application. + + All required parameters must be populated in order to send to Azure. + + :ivar name: The plan name. Required. + :vartype name: str + :ivar publisher: The publisher ID. Required. + :vartype publisher: str + :ivar product: The product code. Required. + :vartype product: str + :ivar promotion_code: The promotion code. + :vartype promotion_code: str + :ivar version: The plan's version. Required. + :vartype version: str + """ + + _validation = { + "name": {"required": True}, + "publisher": {"required": True}, + "product": {"required": True}, + "version": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "publisher": {"key": "publisher", "type": "str"}, + "product": {"key": "product", "type": "str"}, + "promotion_code": {"key": "promotionCode", "type": "str"}, + "version": {"key": "version", "type": "str"}, + } + + def __init__( + self, + *, + name: str, + publisher: str, + product: str, + version: str, + promotion_code: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The plan name. Required. + :paramtype name: str + :keyword publisher: The publisher ID. Required. + :paramtype publisher: str + :keyword product: The product code. Required. + :paramtype product: str + :keyword promotion_code: The promotion code. + :paramtype promotion_code: str + :keyword version: The plan's version. Required. + :paramtype version: str + """ + super().__init__(**kwargs) + self.name = name + self.publisher = publisher + self.product = product + self.promotion_code = promotion_code + self.version = version + + +class PlanPatchable(_serialization.Model): + """Plan for the managed application. + + :ivar name: The plan name. + :vartype name: str + :ivar publisher: The publisher ID. + :vartype publisher: str + :ivar product: The product code. + :vartype product: str + :ivar promotion_code: The promotion code. + :vartype promotion_code: str + :ivar version: The plan's version. + :vartype version: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "publisher": {"key": "publisher", "type": "str"}, + "product": {"key": "product", "type": "str"}, + "promotion_code": {"key": "promotionCode", "type": "str"}, + "version": {"key": "version", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + publisher: Optional[str] = None, + product: Optional[str] = None, + promotion_code: Optional[str] = None, + version: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The plan name. + :paramtype name: str + :keyword publisher: The publisher ID. + :paramtype publisher: str + :keyword product: The product code. + :paramtype product: str + :keyword promotion_code: The promotion code. + :paramtype promotion_code: str + :keyword version: The plan's version. + :paramtype version: str + """ + super().__init__(**kwargs) + self.name = name + self.publisher = publisher + self.product = product + self.promotion_code = promotion_code + self.version = version + + +class Sku(_serialization.Model): + """SKU for the resource. + + All required parameters must be populated in order to send to Azure. + + :ivar name: The SKU name. Required. + :vartype name: str + :ivar tier: The SKU tier. + :vartype tier: str + :ivar size: The SKU size. + :vartype size: str + :ivar family: The SKU family. + :vartype family: str + :ivar model: The SKU model. + :vartype model: str + :ivar capacity: The SKU capacity. + :vartype capacity: int + """ + + _validation = { + "name": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "tier": {"key": "tier", "type": "str"}, + "size": {"key": "size", "type": "str"}, + "family": {"key": "family", "type": "str"}, + "model": {"key": "model", "type": "str"}, + "capacity": {"key": "capacity", "type": "int"}, + } + + def __init__( + self, + *, + name: str, + tier: Optional[str] = None, + size: Optional[str] = None, + family: Optional[str] = None, + model: Optional[str] = None, + capacity: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The SKU name. Required. + :paramtype name: str + :keyword tier: The SKU tier. + :paramtype tier: str + :keyword size: The SKU size. + :paramtype size: str + :keyword family: The SKU family. + :paramtype family: str + :keyword model: The SKU model. + :paramtype model: str + :keyword capacity: The SKU capacity. + :paramtype capacity: int + """ + super().__init__(**kwargs) + self.name = name + self.tier = tier + self.size = size + self.family = family + self.model = model + self.capacity = capacity + + +class UserAssignedResourceIdentity(_serialization.Model): + """Represents the user assigned identity that is contained within the UserAssignedIdentities + dictionary on ResourceIdentity. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal id of user assigned identity. + :vartype principal_id: str + :ivar tenant_id: The tenant id of user assigned identity. + :vartype tenant_id: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.principal_id = None + self.tenant_id = None diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8eb99a2dc9453cb8db10e5ff0241f6954d06b6c7 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/operations/__init__.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import ApplicationClientOperationsMixin +from ._operations import ApplicationsOperations +from ._operations import ApplicationDefinitionsOperations +from ._operations import JitRequestsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "ApplicationClientOperationsMixin", + "ApplicationsOperations", + "ApplicationDefinitionsOperations", + "JitRequestsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..0b60709935cb6b66d6b1001511638d30b64e7f8d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/operations/_operations.py @@ -0,0 +1,3856 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import ApplicationClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_application_list_operations_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Solutions/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_get_request( + resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_delete_request( + resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_create_or_update_request( + resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_update_request( + resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_list_by_resource_group_request( + resource_group_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Solutions/applications") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_get_by_id_request(application_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{applicationId}") + path_format_arguments = { + "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_delete_by_id_request(application_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{applicationId}") + path_format_arguments = { + "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_create_or_update_by_id_request(application_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{applicationId}") + path_format_arguments = { + "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_update_by_id_request(application_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{applicationId}") + path_format_arguments = { + "applicationId": _SERIALIZER.url("application_id", application_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_applications_refresh_permissions_request( + resource_group_name: str, application_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}/refreshPermissions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationName": _SERIALIZER.url("application_name", application_name, "str", max_length=64, min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_get_request( + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_delete_request( + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_create_or_update_request( + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_list_by_resource_group_request( + resource_group_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_get_by_id_request( + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_delete_by_id_request( + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_application_definitions_create_or_update_by_id_request( + resource_group_name: str, application_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "applicationDefinitionName": _SERIALIZER.url( + "application_definition_name", application_definition_name, "str", max_length=64, min_length=3 + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_get_request( + resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_create_or_update_request( + resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_update_request( + resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_delete_request( + resource_group_name: str, jit_request_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "jitRequestName": _SERIALIZER.url("jit_request_name", jit_request_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Solutions/jitRequests") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jit_requests_list_by_resource_group_request( + resource_group_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ApplicationClientOperationsMixin(ApplicationClientMixinABC): + @distributed_trace + def list_operations(self, **kwargs: Any) -> Iterable["_models.Operation"]: + """Lists all of the available Microsoft.Solutions REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_application_list_operations_request( + api_version=api_version, + template_url=self.list_operations.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_operations.metadata = {"url": "/providers/Microsoft.Solutions/operations"} + + +class ApplicationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.v2019_07_01.ApplicationClient`'s + :attr:`applications` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, resource_group_name: str, application_name: str, **kwargs: Any) -> _models.Application: + """Gets the managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + request = build_applications_get_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_applications_delete_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + @distributed_trace + def begin_delete(self, resource_group_name: str, application_name: str, **kwargs: Any) -> LROPoller[None]: + """Deletes the managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + application_name=application_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + def _create_or_update_initial( + self, resource_group_name: str, application_name: str, parameters: Union[_models.Application, IO], **kwargs: Any + ) -> _models.Application: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Application") + + request = build_applications_create_or_update_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("Application", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + application_name: str, + parameters: _models.Application, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + application_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, resource_group_name: str, application_name: str, parameters: Union[_models.Application, IO], **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to the create or update a managed application. Is either + a Application type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + application_name=application_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Application", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + @overload + def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[_models.ApplicationPatchable] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPatchable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[IO] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + resource_group_name: str, + application_name: str, + parameters: Optional[Union[_models.ApplicationPatchable, IO]] = None, + **kwargs: Any + ) -> Optional[_models.Application]: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :param parameters: Parameters supplied to update an existing managed application. Is either a + ApplicationPatchable type or a IO type. Default value is None. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationPatchable or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.Application]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + if parameters is not None: + _json = self._serialize.body(parameters, "ApplicationPatchable") + else: + _json = None + + request = build_applications_update_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}" + } + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Application"]: + """Gets all the applications within a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Application or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_applications_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications" + } + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.Application"]: + """Gets all the applications within a subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Application or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.ApplicationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_applications_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_subscription.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Solutions/applications" + } + + @distributed_trace + def get_by_id(self, application_id: str, **kwargs: Any) -> _models.Application: + """Gets the managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + request = build_applications_get_by_id_request( + application_id=application_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{applicationId}"} + + def _delete_by_id_initial( # pylint: disable=inconsistent-return-statements + self, application_id: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_applications_delete_by_id_request( + application_id=application_id, + api_version=api_version, + template_url=self._delete_by_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_by_id_initial.metadata = {"url": "/{applicationId}"} + + @distributed_trace + def begin_delete_by_id(self, application_id: str, **kwargs: Any) -> LROPoller[None]: + """Deletes the managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_by_id_initial( # type: ignore + application_id=application_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete_by_id.metadata = {"url": "/{applicationId}"} + + def _create_or_update_by_id_initial( + self, application_id: str, parameters: Union[_models.Application, IO], **kwargs: Any + ) -> _models.Application: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Application") + + request = build_applications_create_or_update_by_id_request( + application_id=application_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_by_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("Application", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_by_id_initial.metadata = {"url": "/{applicationId}"} + + @overload + def begin_create_or_update_by_id( + self, + application_id: str, + parameters: _models.Application, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update_by_id( + self, application_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update_by_id( + self, application_id: str, parameters: Union[_models.Application, IO], **kwargs: Any + ) -> LROPoller[_models.Application]: + """Creates a new managed application. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to the create or update a managed application. Is either + a Application type or a IO type. Required. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Application or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_by_id_initial( + application_id=application_id, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Application", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update_by_id.metadata = {"url": "/{applicationId}"} + + @overload + def update_by_id( + self, + application_id: str, + parameters: Optional[_models.Application] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_by_id( + self, + application_id: str, + parameters: Optional[IO] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Default value + is None. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update_by_id( + self, application_id: str, parameters: Optional[Union[_models.Application, IO]] = None, **kwargs: Any + ) -> _models.Application: + """Updates an existing managed application. The only value that can be updated via PATCH currently + is the tags. + + :param application_id: The fully qualified ID of the managed application, including the managed + application name and the managed application resource type. Use the format, + /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applications/{application-name}. + Required. + :type application_id: str + :param parameters: Parameters supplied to update an existing managed application. Is either a + Application type or a IO type. Default value is None. + :type parameters: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Application or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.Application + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Application] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + if parameters is not None: + _json = self._serialize.body(parameters, "Application") + else: + _json = None + + request = build_applications_update_by_id_request( + application_id=application_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Application", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update_by_id.metadata = {"url": "/{applicationId}"} + + def _refresh_permissions_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_applications_refresh_permissions_request( + resource_group_name=resource_group_name, + application_name=application_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._refresh_permissions_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _refresh_permissions_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}/refreshPermissions" + } + + @distributed_trace + def begin_refresh_permissions( + self, resource_group_name: str, application_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Refresh Permissions for application. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_name: The name of the managed application. Required. + :type application_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._refresh_permissions_initial( # type: ignore + resource_group_name=resource_group_name, + application_name=application_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_refresh_permissions.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applications/{applicationName}/refreshPermissions" + } + + +class ApplicationDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.v2019_07_01.ApplicationClient`'s + :attr:`application_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> _models.ApplicationDefinition: + """Gets the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ApplicationDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + request = build_application_definitions_get_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_application_definitions_delete_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + @distributed_trace + def begin_delete( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition to delete. + Required. + :type application_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + def _create_or_update_initial( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO], + **kwargs: Any + ) -> _models.ApplicationDefinition: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ApplicationDefinition") + + request = build_application_definitions_create_or_update_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: _models.ApplicationDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO], + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update an managed application + definition. Is either a ApplicationDefinition type or a IO type. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> Iterable["_models.ApplicationDefinition"]: + """Lists the managed application definitions in a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.ApplicationDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_application_definitions_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ApplicationDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions" + } + + @distributed_trace + def get_by_id( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> _models.ApplicationDefinition: + """Gets the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ApplicationDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + request = build_application_definitions_get_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + def _delete_by_id_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_application_definitions_delete_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_by_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_by_id_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + @distributed_trace + def begin_delete_by_id( + self, resource_group_name: str, application_definition_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes the managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_by_id_initial( # type: ignore + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete_by_id.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + def _create_or_update_by_id_initial( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO], + **kwargs: Any + ) -> _models.ApplicationDefinition: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ApplicationDefinition") + + request = build_application_definitions_create_or_update_by_id_request( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_by_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_by_id_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + @overload + def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: _models.ApplicationDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update_by_id( + self, + resource_group_name: str, + application_definition_name: str, + parameters: Union[_models.ApplicationDefinition, IO], + **kwargs: Any + ) -> LROPoller[_models.ApplicationDefinition]: + """Creates a new managed application definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param application_definition_name: The name of the managed application definition. Required. + :type application_definition_name: str + :param parameters: Parameters supplied to the create or update a managed application + definition. Is either a ApplicationDefinition type or a IO type. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ApplicationDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.ApplicationDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ApplicationDefinition] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_by_id_initial( + resource_group_name=resource_group_name, + application_definition_name=application_definition_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ApplicationDefinition", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update_by_id.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/applicationDefinitions/{applicationDefinitionName}" + } + + +class JitRequestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.managedapplications.v2019_07_01.ApplicationClient`'s + :attr:`jit_requests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, resource_group_name: str, jit_request_name: str, **kwargs: Any) -> _models.JitRequestDefinition: + """Gets the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + + request = build_jit_requests_get_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}" + } + + def _create_or_update_initial( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestDefinition, IO], + **kwargs: Any + ) -> _models.JitRequestDefinition: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "JitRequestDefinition") + + request = build_jit_requests_create_or_update_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("JitRequestDefinition", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("JitRequestDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: _models.JitRequestDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either JitRequestDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either JitRequestDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestDefinition, IO], + **kwargs: Any + ) -> LROPoller[_models.JitRequestDefinition]: + """Creates or updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Is either a + JitRequestDefinition type or a IO type. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either JitRequestDefinition or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("JitRequestDefinition", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}" + } + + @overload + def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: _models.JitRequestPatchable, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestPatchable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + resource_group_name: str, + jit_request_name: str, + parameters: Union[_models.JitRequestPatchable, IO], + **kwargs: Any + ) -> _models.JitRequestDefinition: + """Updates the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :param parameters: Parameters supplied to the update JIT request. Is either a + JitRequestPatchable type or a IO type. Required. + :type parameters: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestPatchable or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JitRequestDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "JitRequestPatchable") + + request = build_jit_requests_update_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}" + } + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, jit_request_name: str, **kwargs: Any + ) -> None: + """Deletes the JIT request. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param jit_request_name: The name of the JIT request. Required. + :type jit_request_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_jit_requests_delete_request( + resource_group_name=resource_group_name, + jit_request_name=jit_request_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests/{jitRequestName}" + } + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> _models.JitRequestDefinitionListResult: + """Retrieves all JIT requests within the subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinitionListResult or the result of cls(response) + :rtype: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinitionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) + + request = build_jit_requests_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Solutions/jitRequests"} + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> _models.JitRequestDefinitionListResult: + """Retrieves all JIT requests within the resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: JitRequestDefinitionListResult or the result of cls(response) + :rtype: + ~azure.mgmt.resource.managedapplications.v2019_07_01.models.JitRequestDefinitionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2019-07-01"] = kwargs.pop("api_version", _params.pop("api-version", "2019-07-01")) + cls: ClsType[_models.JitRequestDefinitionListResult] = kwargs.pop("cls", None) + + request = build_jit_requests_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("JitRequestDefinitionListResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Solutions/jitRequests" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/managedapplications/v2019_07_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67097cd4cd1b68e8bd68e10b832c789acee8ef5d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._policy_client import PolicyClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..818eef3454653482e9971037cd2ba7f43a2d8c4f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class PolicyClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for PolicyClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-10-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(PolicyClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2015-10-01-preview"] = kwargs.pop("api_version", "2015-10-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/_policy_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/_policy_client.py new file mode 100644 index 0000000000000000000000000000000000000000..da9a09845099360251c16cc9be665802cde9b29d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/_policy_client.py @@ -0,0 +1,97 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import PolicyClientConfiguration +from .operations import PolicyAssignmentsOperations, PolicyDefinitionsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class PolicyClient: # pylint: disable=client-accepts-api-version-keyword + """To manage and control access to your resources, you can define customized policies and assign + them at a scope. + + :ivar policy_assignments: PolicyAssignmentsOperations operations + :vartype policy_assignments: + azure.mgmt.resource.policy.v2015_10_01_preview.aio.operations.PolicyAssignmentsOperations + :ivar policy_definitions: PolicyDefinitionsOperations operations + :vartype policy_definitions: + azure.mgmt.resource.policy.v2015_10_01_preview.aio.operations.PolicyDefinitionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2015-10-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = PolicyClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.policy_assignments = PolicyAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_definitions = PolicyDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "PolicyClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07e31530091e628e745cf78b8729dd8953998a81 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import PolicyAssignmentsOperations +from ._operations import PolicyDefinitionsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyAssignmentsOperations", + "PolicyDefinitionsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..6f2aa36b66f4688568d7a89023ec92a1611f626d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/operations/_operations.py @@ -0,0 +1,1256 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_policy_assignments_create_by_id_request, + build_policy_assignments_create_request, + build_policy_assignments_delete_by_id_request, + build_policy_assignments_delete_request, + build_policy_assignments_get_by_id_request, + build_policy_assignments_get_request, + build_policy_assignments_list_for_resource_group_request, + build_policy_assignments_list_for_resource_request, + build_policy_assignments_list_request, + build_policy_definitions_create_or_update_request, + build_policy_definitions_delete_request, + build_policy_definitions_get_request, + build_policy_definitions_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2015_10_01_preview.aio.PolicyClient`'s + :attr:`policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> _models.PolicyAssignment: + """Deletes a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to delete. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, scope: str, policy_assignment_name: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @distributed_trace_async + async def get(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to get. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets policy assignments for the resource group. + + :param resource_group_name: The name of the resource group that contains policy assignments. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments" + } + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets policy assignments for a resource. + + :param resource_group_name: The name of the resource group containing the resource. The name is + case insensitive. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Required. + :type parent_resource_path: str + :param resource_type: The resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource with policy assignments. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyassignments" + } + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets all the policy assignments for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyassignments"} + + @distributed_trace_async + async def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Deletes a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to delete. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @overload + async def create_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, policy_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @distributed_trace_async + async def get_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to get. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{policyAssignmentId}"} + + +class PolicyDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2015_10_01_preview.aio.PolicyClient`'s + :attr:`policy_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, policy_definition_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO], **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + request = build_policy_definitions_create_or_update_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_definitions_delete_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Gets the policy definition. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.PolicyDefinition"]: + """Gets all the policy definitions for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..506c980bd67be5e12fa4b662c52cd3dcbd11797f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import PolicyAssignment +from ._models_py3 import PolicyAssignmentListResult +from ._models_py3 import PolicyDefinition +from ._models_py3 import PolicyDefinitionListResult + +from ._policy_client_enums import PolicyType +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyAssignment", + "PolicyAssignmentListResult", + "PolicyDefinition", + "PolicyDefinitionListResult", + "PolicyType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..e62f3c3aac6999fc5b25389bad98fbc52fa2ca0c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/_models_py3.py @@ -0,0 +1,215 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + + +class PolicyAssignment(_serialization.Model): + """The policy assignment. + + :ivar id: The ID of the policy assignment. + :vartype id: str + :ivar type: The type of the policy assignment. + :vartype type: str + :ivar name: The name of the policy assignment. + :vartype name: str + :ivar display_name: The display name of the policy assignment. + :vartype display_name: str + :ivar policy_definition_id: The ID of the policy definition. + :vartype policy_definition_id: str + :ivar scope: The scope for the policy assignment. + :vartype scope: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "policy_definition_id": {"key": "properties.policyDefinitionId", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + type: Optional[str] = None, + name: Optional[str] = None, + display_name: Optional[str] = None, + policy_definition_id: Optional[str] = None, + scope: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The ID of the policy assignment. + :paramtype id: str + :keyword type: The type of the policy assignment. + :paramtype type: str + :keyword name: The name of the policy assignment. + :paramtype name: str + :keyword display_name: The display name of the policy assignment. + :paramtype display_name: str + :keyword policy_definition_id: The ID of the policy definition. + :paramtype policy_definition_id: str + :keyword scope: The scope for the policy assignment. + :paramtype scope: str + """ + super().__init__(**kwargs) + self.id = id + self.type = type + self.name = name + self.display_name = display_name + self.policy_definition_id = policy_definition_id + self.scope = scope + + +class PolicyAssignmentListResult(_serialization.Model): + """List of policy assignments. + + :ivar value: An array of policy assignments. + :vartype value: list[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.PolicyAssignment"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy assignments. + :paramtype value: list[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicyDefinition(_serialization.Model): + """The policy definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy definition. + :vartype id: str + :ivar name: The name of the policy definition. If you do not specify a value for name, the + value is inferred from the name value in the request URI. + :vartype name: str + :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + and Custom. Known values are: "NotSpecified", "BuiltIn", and "Custom". + :vartype policy_type: str or ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyType + :ivar display_name: The display name of the policy definition. + :vartype display_name: str + :ivar description: The policy definition description. + :vartype description: str + :ivar policy_rule: The policy rule. + :vartype policy_rule: JSON + """ + + _validation = { + "id": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "policy_type": {"key": "properties.policyType", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "policy_rule": {"key": "properties.policyRule", "type": "object"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + policy_type: Optional[Union[str, "_models.PolicyType"]] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + policy_rule: Optional[JSON] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of the policy definition. If you do not specify a value for name, the + value is inferred from the name value in the request URI. + :paramtype name: str + :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + and Custom. Known values are: "NotSpecified", "BuiltIn", and "Custom". + :paramtype policy_type: str or + ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyType + :keyword display_name: The display name of the policy definition. + :paramtype display_name: str + :keyword description: The policy definition description. + :paramtype description: str + :keyword policy_rule: The policy rule. + :paramtype policy_rule: JSON + """ + super().__init__(**kwargs) + self.id = None + self.name = name + self.policy_type = policy_type + self.display_name = display_name + self.description = description + self.policy_rule = policy_rule + + +class PolicyDefinitionListResult(_serialization.Model): + """List of policy definitions. + + :ivar value: An array of policy definitions. + :vartype value: list[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.PolicyDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy definitions. + :paramtype value: list[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/_policy_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/_policy_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..91c08bdc295c31d59c2cdf8d734a4f19e3dde5d0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/models/_policy_client_enums.py @@ -0,0 +1,18 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class PolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom.""" + + NOT_SPECIFIED = "NotSpecified" + BUILT_IN = "BuiltIn" + CUSTOM = "Custom" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07e31530091e628e745cf78b8729dd8953998a81 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import PolicyAssignmentsOperations +from ._operations import PolicyDefinitionsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyAssignmentsOperations", + "PolicyDefinitionsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..2ed2ab656283b2f718dbf50ef02d1236e785bbd0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/operations/_operations.py @@ -0,0 +1,1656 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_policy_assignments_delete_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_create_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_get_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_resource_group_request( + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyassignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_request( + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyassignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_delete_by_id_request(policy_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_create_by_id_request(policy_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_get_by_id_request(policy_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_create_or_update_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_delete_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_policy_definitions_get_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_list_request( + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2015_10_01_preview.PolicyClient`'s + :attr:`policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> _models.PolicyAssignment: + """Deletes a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to delete. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @overload + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, scope: str, policy_assignment_name: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @distributed_trace + def get(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to get. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.PolicyAssignment"]: + """Gets policy assignments for the resource group. + + :param resource_group_name: The name of the resource group that contains policy assignments. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments" + } + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyAssignment"]: + """Gets policy assignments for a resource. + + :param resource_group_name: The name of the resource group containing the resource. The name is + case insensitive. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Required. + :type parent_resource_path: str + :param resource_type: The resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource with policy assignments. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyassignments" + } + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.PolicyAssignment"]: + """Gets all the policy assignments for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyassignments"} + + @distributed_trace + def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Deletes a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to delete. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @overload + def create_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_by_id( + self, policy_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @distributed_trace + def get_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to get. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{policyAssignmentId}"} + + +class PolicyDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2015_10_01_preview.PolicyClient`'s + :attr:`policy_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, policy_definition_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO], **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + request = build_policy_definitions_create_or_update_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_definitions_delete_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace + def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Gets the policy definition. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.PolicyDefinition"]: + """Gets all the policy definitions for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2015_10_01_preview.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2015-10-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2015-10-01-preview") + ) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2015_10_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67097cd4cd1b68e8bd68e10b832c789acee8ef5d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._policy_client import PolicyClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..7dae5cd1d493d3613be0991ead213bfd76621494 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class PolicyClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for PolicyClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2016-04-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(PolicyClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", "2016-04-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/_policy_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/_policy_client.py new file mode 100644 index 0000000000000000000000000000000000000000..57858ac5062a186285625ccd98daf7bd336310a8 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/_policy_client.py @@ -0,0 +1,97 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import PolicyClientConfiguration +from .operations import PolicyAssignmentsOperations, PolicyDefinitionsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class PolicyClient: # pylint: disable=client-accepts-api-version-keyword + """To manage and control access to your resources, you can define customized policies and assign + them at a scope. + + :ivar policy_assignments: PolicyAssignmentsOperations operations + :vartype policy_assignments: + azure.mgmt.resource.policy.v2016_04_01.aio.operations.PolicyAssignmentsOperations + :ivar policy_definitions: PolicyDefinitionsOperations operations + :vartype policy_definitions: + azure.mgmt.resource.policy.v2016_04_01.aio.operations.PolicyDefinitionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2016-04-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = PolicyClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.policy_assignments = PolicyAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_definitions = PolicyDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "PolicyClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07e31530091e628e745cf78b8729dd8953998a81 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import PolicyAssignmentsOperations +from ._operations import PolicyDefinitionsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyAssignmentsOperations", + "PolicyDefinitionsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..fcff231ee6679a28b91dee44bc24c65f14f45660 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/operations/_operations.py @@ -0,0 +1,1230 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_policy_assignments_create_by_id_request, + build_policy_assignments_create_request, + build_policy_assignments_delete_by_id_request, + build_policy_assignments_delete_request, + build_policy_assignments_get_by_id_request, + build_policy_assignments_get_request, + build_policy_assignments_list_for_resource_group_request, + build_policy_assignments_list_for_resource_request, + build_policy_assignments_list_request, + build_policy_definitions_create_or_update_request, + build_policy_definitions_delete_request, + build_policy_definitions_get_request, + build_policy_definitions_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2016_04_01.aio.PolicyClient`'s + :attr:`policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> _models.PolicyAssignment: + """Deletes a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to delete. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, scope: str, policy_assignment_name: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @distributed_trace_async + async def get(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to get. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets policy assignments for the resource group. + + :param resource_group_name: The name of the resource group that contains policy assignments. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments" + } + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets policy assignments for a resource. + + :param resource_group_name: The name of the resource group containing the resource. The name is + case insensitive. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Required. + :type parent_resource_path: str + :param resource_type: The resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource with policy assignments. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyassignments" + } + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets all the policy assignments for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyassignments"} + + @distributed_trace_async + async def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Deletes a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to delete. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @overload + async def create_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, policy_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @distributed_trace_async + async def get_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to get. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{policyAssignmentId}"} + + +class PolicyDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2016_04_01.aio.PolicyClient`'s + :attr:`policy_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, policy_definition_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO], **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + request = build_policy_definitions_create_or_update_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_definitions_delete_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Gets the policy definition. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.PolicyDefinition"]: + """Gets all the policy definitions for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..506c980bd67be5e12fa4b662c52cd3dcbd11797f --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/__init__.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import PolicyAssignment +from ._models_py3 import PolicyAssignmentListResult +from ._models_py3 import PolicyDefinition +from ._models_py3 import PolicyDefinitionListResult + +from ._policy_client_enums import PolicyType +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyAssignment", + "PolicyAssignmentListResult", + "PolicyDefinition", + "PolicyDefinitionListResult", + "PolicyType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..7f505fda35401b673e86729c506888201ebf20a1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/_models_py3.py @@ -0,0 +1,214 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + + +class PolicyAssignment(_serialization.Model): + """The policy assignment. + + :ivar id: The ID of the policy assignment. + :vartype id: str + :ivar type: The type of the policy assignment. + :vartype type: str + :ivar name: The name of the policy assignment. + :vartype name: str + :ivar display_name: The display name of the policy assignment. + :vartype display_name: str + :ivar policy_definition_id: The ID of the policy definition. + :vartype policy_definition_id: str + :ivar scope: The scope for the policy assignment. + :vartype scope: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "policy_definition_id": {"key": "properties.policyDefinitionId", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + type: Optional[str] = None, + name: Optional[str] = None, + display_name: Optional[str] = None, + policy_definition_id: Optional[str] = None, + scope: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The ID of the policy assignment. + :paramtype id: str + :keyword type: The type of the policy assignment. + :paramtype type: str + :keyword name: The name of the policy assignment. + :paramtype name: str + :keyword display_name: The display name of the policy assignment. + :paramtype display_name: str + :keyword policy_definition_id: The ID of the policy definition. + :paramtype policy_definition_id: str + :keyword scope: The scope for the policy assignment. + :paramtype scope: str + """ + super().__init__(**kwargs) + self.id = id + self.type = type + self.name = name + self.display_name = display_name + self.policy_definition_id = policy_definition_id + self.scope = scope + + +class PolicyAssignmentListResult(_serialization.Model): + """List of policy assignments. + + :ivar value: An array of policy assignments. + :vartype value: list[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.PolicyAssignment"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy assignments. + :paramtype value: list[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicyDefinition(_serialization.Model): + """The policy definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy definition. + :vartype id: str + :ivar name: The name of the policy definition. If you do not specify a value for name, the + value is inferred from the name value in the request URI. + :vartype name: str + :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + and Custom. Known values are: "NotSpecified", "BuiltIn", and "Custom". + :vartype policy_type: str or ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyType + :ivar display_name: The display name of the policy definition. + :vartype display_name: str + :ivar description: The policy definition description. + :vartype description: str + :ivar policy_rule: The policy rule. + :vartype policy_rule: JSON + """ + + _validation = { + "id": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "policy_type": {"key": "properties.policyType", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "policy_rule": {"key": "properties.policyRule", "type": "object"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + policy_type: Optional[Union[str, "_models.PolicyType"]] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + policy_rule: Optional[JSON] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of the policy definition. If you do not specify a value for name, the + value is inferred from the name value in the request URI. + :paramtype name: str + :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + and Custom. Known values are: "NotSpecified", "BuiltIn", and "Custom". + :paramtype policy_type: str or ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyType + :keyword display_name: The display name of the policy definition. + :paramtype display_name: str + :keyword description: The policy definition description. + :paramtype description: str + :keyword policy_rule: The policy rule. + :paramtype policy_rule: JSON + """ + super().__init__(**kwargs) + self.id = None + self.name = name + self.policy_type = policy_type + self.display_name = display_name + self.description = description + self.policy_rule = policy_rule + + +class PolicyDefinitionListResult(_serialization.Model): + """List of policy definitions. + + :ivar value: An array of policy definitions. + :vartype value: list[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.PolicyDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy definitions. + :paramtype value: list[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/_policy_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/_policy_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..91c08bdc295c31d59c2cdf8d734a4f19e3dde5d0 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/models/_policy_client_enums.py @@ -0,0 +1,18 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class PolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom.""" + + NOT_SPECIFIED = "NotSpecified" + BUILT_IN = "BuiltIn" + CUSTOM = "Custom" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07e31530091e628e745cf78b8729dd8953998a81 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import PolicyAssignmentsOperations +from ._operations import PolicyDefinitionsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyAssignmentsOperations", + "PolicyDefinitionsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..cd94f79a8e9cef1e8309e5840711e88bd759f325 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/operations/_operations.py @@ -0,0 +1,1604 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_policy_assignments_delete_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_create_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_get_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_resource_group_request( + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyassignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_request( + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyassignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_delete_by_id_request(policy_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_create_by_id_request(policy_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_get_by_id_request(policy_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_create_or_update_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_delete_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_policy_definitions_get_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_list_request( + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2016_04_01.PolicyClient`'s + :attr:`policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> _models.PolicyAssignment: + """Deletes a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to delete. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @overload + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, scope: str, policy_assignment_name: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @distributed_trace + def get(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to get. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyassignments/{policyAssignmentName}"} + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.PolicyAssignment"]: + """Gets policy assignments for the resource group. + + :param resource_group_name: The name of the resource group that contains policy assignments. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments" + } + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyAssignment"]: + """Gets policy assignments for a resource. + + :param resource_group_name: The name of the resource group containing the resource. The name is + case insensitive. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Required. + :type parent_resource_path: str + :param resource_type: The resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource with policy assignments. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyassignments" + } + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.PolicyAssignment"]: + """Gets all the policy assignments for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyassignments"} + + @distributed_trace + def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Deletes a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to delete. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @overload + def create_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_by_id( + self, policy_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @distributed_trace + def get_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to get. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{policyAssignmentId}"} + + +class PolicyDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2016_04_01.PolicyClient`'s + :attr:`policy_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, policy_definition_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO], **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + request = build_policy_definitions_create_or_update_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_definitions_delete_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace + def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Gets the policy definition. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}" + } + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.PolicyDefinition"]: + """Gets all the policy definitions for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_04_01.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-04-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_04_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67097cd4cd1b68e8bd68e10b832c789acee8ef5d --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._policy_client import PolicyClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/_configuration.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..b276431cee29570cb738208c61bd3f06cca71a16 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class PolicyClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for PolicyClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2016-12-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(PolicyClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", "2016-12-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/_policy_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/_policy_client.py new file mode 100644 index 0000000000000000000000000000000000000000..5a292f90024800555ad660f6d129c24be9fc3ae1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/_policy_client.py @@ -0,0 +1,97 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import PolicyClientConfiguration +from .operations import PolicyAssignmentsOperations, PolicyDefinitionsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class PolicyClient: # pylint: disable=client-accepts-api-version-keyword + """To manage and control access to your resources, you can define customized policies and assign + them at a scope. + + :ivar policy_definitions: PolicyDefinitionsOperations operations + :vartype policy_definitions: + azure.mgmt.resource.policy.v2016_12_01.aio.operations.PolicyDefinitionsOperations + :ivar policy_assignments: PolicyAssignmentsOperations operations + :vartype policy_assignments: + azure.mgmt.resource.policy.v2016_12_01.aio.operations.PolicyAssignmentsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2016-12-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = PolicyClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.policy_definitions = PolicyDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_assignments = PolicyAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "PolicyClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b1086b37ca2ded0bf602da0ee42dbcb7c92030 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import PolicyDefinitionsOperations +from ._operations import PolicyAssignmentsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyDefinitionsOperations", + "PolicyAssignmentsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5d6e65caca3cfda702b3f8e34625e8f18c2aa1 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/operations/_operations.py @@ -0,0 +1,1717 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_policy_assignments_create_by_id_request, + build_policy_assignments_create_request, + build_policy_assignments_delete_by_id_request, + build_policy_assignments_delete_request, + build_policy_assignments_get_by_id_request, + build_policy_assignments_get_request, + build_policy_assignments_list_for_resource_group_request, + build_policy_assignments_list_for_resource_request, + build_policy_assignments_list_request, + build_policy_definitions_create_or_update_at_management_group_request, + build_policy_definitions_create_or_update_request, + build_policy_definitions_delete_at_management_group_request, + build_policy_definitions_delete_request, + build_policy_definitions_get_at_management_group_request, + build_policy_definitions_get_built_in_request, + build_policy_definitions_get_request, + build_policy_definitions_list_built_in_request, + build_policy_definitions_list_by_management_group_request, + build_policy_definitions_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PolicyDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2016_12_01.aio.PolicyClient`'s + :attr:`policy_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, policy_definition_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO], **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + request = build_policy_definitions_create_or_update_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_definitions_delete_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Gets the policy definition. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def get_built_in(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Gets the built in policy definition. + + :param policy_definition_name: The name of the built in policy definition to get. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_built_in_request( + policy_definition_name=policy_definition_name, + api_version=api_version, + template_url=self.get_built_in.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_built_in.metadata = {"url": "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}"} + + @overload + async def create_or_update_at_management_group( + self, + policy_definition_name: str, + management_group_id: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + policy_definition_name: str, + management_group_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + policy_definition_name: str, + management_group_id: str, + parameters: Union[_models.PolicyDefinition, IO], + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + request = build_policy_definitions_create_or_update_at_management_group_request( + policy_definition_name=policy_definition_name, + management_group_id=management_group_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, management_group_id: str, **kwargs: Any + ) -> None: + """Deletes a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_definitions_delete_at_management_group_request( + policy_definition_name=policy_definition_name, + management_group_id=management_group_id, + api_version=api_version, + template_url=self.delete_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def get_at_management_group( + self, policy_definition_name: str, management_group_id: str, **kwargs: Any + ) -> _models.PolicyDefinition: + """Gets the policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_at_management_group_request( + policy_definition_name=policy_definition_name, + management_group_id=management_group_id, + api_version=api_version, + template_url=self.get_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.PolicyDefinition"]: + """Gets all the policy definitions for a subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions"} + + @distributed_trace + def list_built_in(self, **kwargs: Any) -> AsyncIterable["_models.PolicyDefinition"]: + """Gets all the built in policy definitions. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_built_in_request( + api_version=api_version, + template_url=self.list_built_in.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_built_in.metadata = {"url": "/providers/Microsoft.Authorization/policyDefinitions"} + + @distributed_trace + def list_by_management_group( + self, management_group_id: str, **kwargs: Any + ) -> AsyncIterable["_models.PolicyDefinition"]: + """Gets all the policy definitions for a subscription at management group level. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_by_management_group_request( + management_group_id=management_group_id, + api_version=api_version, + template_url=self.list_by_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions" + } + + +class PolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2016_12_01.aio.PolicyClient`'s + :attr:`policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete( + self, scope: str, policy_assignment_name: str, **kwargs: Any + ) -> Optional[_models.PolicyAssignment]: + """Deletes a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to delete. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}"} + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, scope: str, policy_assignment_name: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}"} + + @distributed_trace_async + async def get(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to get. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}"} + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets policy assignments for the resource group. + + :param resource_group_name: The name of the resource group that contains policy assignments. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments" + } + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets policy assignments for a resource. + + :param resource_group_name: The name of the resource group containing the resource. The name is + case insensitive. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Required. + :type parent_resource_path: str + :param resource_type: The resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource with policy assignments. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments" + } + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets all the policy assignments for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments"} + + @distributed_trace_async + async def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Deletes a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to delete. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @overload + async def create_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, policy_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @distributed_trace_async + async def get_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to get. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{policyAssignmentId}"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..411a45823afa449371f7d2de61966008f2cb0638 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models_py3 import PolicyAssignment +from ._models_py3 import PolicyAssignmentListResult +from ._models_py3 import PolicyDefinition +from ._models_py3 import PolicyDefinitionListResult + +from ._policy_client_enums import PolicyMode +from ._policy_client_enums import PolicyType +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyAssignment", + "PolicyAssignmentListResult", + "PolicyDefinition", + "PolicyDefinitionListResult", + "PolicyMode", + "PolicyType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/_models_py3.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/_models_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..e77ee2dc9fbfbb9daddf80c2c1c393ae487d2b73 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/_models_py3.py @@ -0,0 +1,250 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + + +class PolicyAssignment(_serialization.Model): + """The policy assignment. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy assignment. + :vartype id: str + :ivar type: The type of the policy assignment. + :vartype type: str + :ivar name: The name of the policy assignment. + :vartype name: str + :ivar display_name: The display name of the policy assignment. + :vartype display_name: str + :ivar policy_definition_id: The ID of the policy definition. + :vartype policy_definition_id: str + :ivar scope: The scope for the policy assignment. + :vartype scope: str + :ivar parameters: Required if a parameter is used in policy rule. + :vartype parameters: JSON + :ivar description: This message will be part of response in case of policy violation. + :vartype description: str + """ + + _validation = { + "id": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "policy_definition_id": {"key": "properties.policyDefinitionId", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "parameters": {"key": "properties.parameters", "type": "object"}, + "description": {"key": "properties.description", "type": "str"}, + } + + def __init__( + self, + *, + type: Optional[str] = None, + name: Optional[str] = None, + display_name: Optional[str] = None, + policy_definition_id: Optional[str] = None, + scope: Optional[str] = None, + parameters: Optional[JSON] = None, + description: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: The type of the policy assignment. + :paramtype type: str + :keyword name: The name of the policy assignment. + :paramtype name: str + :keyword display_name: The display name of the policy assignment. + :paramtype display_name: str + :keyword policy_definition_id: The ID of the policy definition. + :paramtype policy_definition_id: str + :keyword scope: The scope for the policy assignment. + :paramtype scope: str + :keyword parameters: Required if a parameter is used in policy rule. + :paramtype parameters: JSON + :keyword description: This message will be part of response in case of policy violation. + :paramtype description: str + """ + super().__init__(**kwargs) + self.id = None + self.type = type + self.name = name + self.display_name = display_name + self.policy_definition_id = policy_definition_id + self.scope = scope + self.parameters = parameters + self.description = description + + +class PolicyAssignmentListResult(_serialization.Model): + """List of policy assignments. + + :ivar value: An array of policy assignments. + :vartype value: list[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.PolicyAssignment"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy assignments. + :paramtype value: list[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicyDefinition(_serialization.Model): + """The policy definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy definition. + :vartype id: str + :ivar name: The name of the policy definition. + :vartype name: str + :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + and Custom. Known values are: "NotSpecified", "BuiltIn", and "Custom". + :vartype policy_type: str or ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyType + :ivar mode: The policy definition mode. Possible values are NotSpecified, Indexed, and All. + Known values are: "NotSpecified", "Indexed", and "All". + :vartype mode: str or ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyMode + :ivar display_name: The display name of the policy definition. + :vartype display_name: str + :ivar description: The policy definition description. + :vartype description: str + :ivar policy_rule: The policy rule. + :vartype policy_rule: JSON + :ivar metadata: The policy definition metadata. + :vartype metadata: JSON + :ivar parameters: Required if a parameter is used in policy rule. + :vartype parameters: JSON + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "policy_type": {"key": "properties.policyType", "type": "str"}, + "mode": {"key": "properties.mode", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "policy_rule": {"key": "properties.policyRule", "type": "object"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "parameters": {"key": "properties.parameters", "type": "object"}, + } + + def __init__( + self, + *, + policy_type: Optional[Union[str, "_models.PolicyType"]] = None, + mode: Optional[Union[str, "_models.PolicyMode"]] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + policy_rule: Optional[JSON] = None, + metadata: Optional[JSON] = None, + parameters: Optional[JSON] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + and Custom. Known values are: "NotSpecified", "BuiltIn", and "Custom". + :paramtype policy_type: str or ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyType + :keyword mode: The policy definition mode. Possible values are NotSpecified, Indexed, and All. + Known values are: "NotSpecified", "Indexed", and "All". + :paramtype mode: str or ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyMode + :keyword display_name: The display name of the policy definition. + :paramtype display_name: str + :keyword description: The policy definition description. + :paramtype description: str + :keyword policy_rule: The policy rule. + :paramtype policy_rule: JSON + :keyword metadata: The policy definition metadata. + :paramtype metadata: JSON + :keyword parameters: Required if a parameter is used in policy rule. + :paramtype parameters: JSON + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.policy_type = policy_type + self.mode = mode + self.display_name = display_name + self.description = description + self.policy_rule = policy_rule + self.metadata = metadata + self.parameters = parameters + + +class PolicyDefinitionListResult(_serialization.Model): + """List of policy definitions. + + :ivar value: An array of policy definitions. + :vartype value: list[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.PolicyDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy definitions. + :paramtype value: list[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/_policy_client_enums.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/_policy_client_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..5a5cb27e9884c54244507990d14194253526807e --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/models/_policy_client_enums.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class PolicyMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The policy definition mode. Possible values are NotSpecified, Indexed, and All.""" + + NOT_SPECIFIED = "NotSpecified" + INDEXED = "Indexed" + ALL = "All" + + +class PolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom.""" + + NOT_SPECIFIED = "NotSpecified" + BUILT_IN = "BuiltIn" + CUSTOM = "Custom" diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b1086b37ca2ded0bf602da0ee42dbcb7c92030 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/operations/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import PolicyDefinitionsOperations +from ._operations import PolicyAssignmentsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyDefinitionsOperations", + "PolicyAssignmentsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..a8f415979506e7077b8b606165d76c2b58ca466b --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/operations/_operations.py @@ -0,0 +1,2234 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_policy_definitions_create_or_update_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_delete_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_policy_definitions_get_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_get_built_in_request(policy_definition_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}") + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_create_or_update_at_management_group_request( + policy_definition_name: str, management_group_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_delete_at_management_group_request( + policy_definition_name: str, management_group_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_policy_definitions_get_at_management_group_request( + policy_definition_name: str, management_group_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_list_built_in_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/policyDefinitions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_list_by_management_group_request(management_group_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_delete_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_create_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_get_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_resource_group_request( + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_resource_request( + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_request( + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_delete_by_id_request(policy_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_create_by_id_request(policy_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_get_by_id_request(policy_assignment_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + accept = _headers.pop("Accept", "application/json, text/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PolicyDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2016_12_01.PolicyClient`'s + :attr:`policy_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, policy_definition_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO], **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + request = build_policy_definitions_create_or_update_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_definitions_delete_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace + def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Gets the policy definition. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace + def get_built_in(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Gets the built in policy definition. + + :param policy_definition_name: The name of the built in policy definition to get. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_built_in_request( + policy_definition_name=policy_definition_name, + api_version=api_version, + template_url=self.get_built_in.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_built_in.metadata = {"url": "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}"} + + @overload + def create_or_update_at_management_group( + self, + policy_definition_name: str, + management_group_id: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + policy_definition_name: str, + management_group_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + policy_definition_name: str, + management_group_id: str, + parameters: Union[_models.PolicyDefinition, IO], + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + request = build_policy_definitions_create_or_update_at_management_group_request( + policy_definition_name=policy_definition_name, + management_group_id=management_group_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, management_group_id: str, **kwargs: Any + ) -> None: + """Deletes a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_definitions_delete_at_management_group_request( + policy_definition_name=policy_definition_name, + management_group_id=management_group_id, + api_version=api_version, + template_url=self.delete_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace + def get_at_management_group( + self, policy_definition_name: str, management_group_id: str, **kwargs: Any + ) -> _models.PolicyDefinition: + """Gets the policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_at_management_group_request( + policy_definition_name=policy_definition_name, + management_group_id=management_group_id, + api_version=api_version, + template_url=self.get_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.PolicyDefinition"]: + """Gets all the policy definitions for a subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions"} + + @distributed_trace + def list_built_in(self, **kwargs: Any) -> Iterable["_models.PolicyDefinition"]: + """Gets all the built in policy definitions. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_built_in_request( + api_version=api_version, + template_url=self.list_built_in.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_built_in.metadata = {"url": "/providers/Microsoft.Authorization/policyDefinitions"} + + @distributed_trace + def list_by_management_group(self, management_group_id: str, **kwargs: Any) -> Iterable["_models.PolicyDefinition"]: + """Gets all the policy definitions for a subscription at management group level. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_by_management_group_request( + management_group_id=management_group_id, + api_version=api_version, + template_url=self.list_by_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions" + } + + +class PolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2016_12_01.PolicyClient`'s + :attr:`policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> Optional[_models.PolicyAssignment]: + """Deletes a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to delete. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}"} + + @overload + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, scope: str, policy_assignment_name: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}"} + + @distributed_trace + def get(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to get. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}"} + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.PolicyAssignment"]: + """Gets policy assignments for the resource group. + + :param resource_group_name: The name of the resource group that contains policy assignments. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments" + } + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyAssignment"]: + """Gets policy assignments for a resource. + + :param resource_group_name: The name of the resource group containing the resource. The name is + case insensitive. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Required. + :type parent_resource_path: str + :param resource_type: The resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource with policy assignments. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments" + } + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.PolicyAssignment"]: + """Gets all the policy assignments for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments"} + + @distributed_trace + def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Deletes a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to delete. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @overload + def create_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_by_id( + self, policy_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @distributed_trace + def get_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to get. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{policyAssignmentId}"} diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2016_12_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2017_06_01_preview/aio/operations/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2017_06_01_preview/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a1b6342ce8939c7fa3193ba101bba73fdf5e964 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2017_06_01_preview/aio/operations/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import PolicyAssignmentsOperations +from ._operations import PolicySetDefinitionsOperations +from ._operations import PolicyDefinitionsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyAssignmentsOperations", + "PolicySetDefinitionsOperations", + "PolicyDefinitionsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2017_06_01_preview/aio/operations/_operations.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2017_06_01_preview/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..f7616e068823f62b1c66b5940bf114823db2d8c3 --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2017_06_01_preview/aio/operations/_operations.py @@ -0,0 +1,2510 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import ( + build_policy_assignments_create_by_id_request, + build_policy_assignments_create_request, + build_policy_assignments_delete_by_id_request, + build_policy_assignments_delete_request, + build_policy_assignments_get_by_id_request, + build_policy_assignments_get_request, + build_policy_assignments_list_for_resource_group_request, + build_policy_assignments_list_for_resource_request, + build_policy_assignments_list_request, + build_policy_definitions_create_or_update_at_management_group_request, + build_policy_definitions_create_or_update_request, + build_policy_definitions_delete_at_management_group_request, + build_policy_definitions_delete_request, + build_policy_definitions_get_at_management_group_request, + build_policy_definitions_get_built_in_request, + build_policy_definitions_get_request, + build_policy_definitions_list_built_in_request, + build_policy_definitions_list_by_management_group_request, + build_policy_definitions_list_request, + build_policy_set_definitions_create_or_update_at_management_group_request, + build_policy_set_definitions_create_or_update_request, + build_policy_set_definitions_delete_at_management_group_request, + build_policy_set_definitions_delete_request, + build_policy_set_definitions_get_at_management_group_request, + build_policy_set_definitions_get_built_in_request, + build_policy_set_definitions_get_request, + build_policy_set_definitions_list_built_in_request, + build_policy_set_definitions_list_by_management_group_request, + build_policy_set_definitions_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2017_06_01_preview.aio.PolicyClient`'s + :attr:`policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete( + self, scope: str, policy_assignment_name: str, **kwargs: Any + ) -> Optional[_models.PolicyAssignment]: + """Deletes a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to delete. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}"} + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, scope: str, policy_assignment_name: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a + IO type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}"} + + @distributed_trace_async + async def get(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment. + + :param scope: The scope of the policy assignment. Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to get. Required. + :type policy_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}"} + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets policy assignments for the resource group. + + :param resource_group_name: The name of the resource group that contains policy assignments. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments" + } + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets policy assignments for a resource. + + :param resource_group_name: The name of the resource group containing the resource. The name is + case insensitive. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Required. + :type parent_resource_path: str + :param resource_type: The resource type. Required. + :type resource_type: str + :param resource_name: The name of the resource with policy assignments. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_for_resource.metadata = { + "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments" + } + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.PolicyAssignment"]: + """Gets all the policy assignments for a subscription. + + :param filter: The filter to apply on the operation. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_assignments_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments"} + + @distributed_trace_async + async def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Deletes a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to delete. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_delete_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.delete_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + delete_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @overload + async def create_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, policy_assignment_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates a policy assignment by ID. + + Policy assignments are inherited by child resources. For example, when you apply a policy to a + resource group that policy is assigned to all resources in the group. When providing a scope + for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions, + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, + and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + request = build_policy_assignments_create_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_by_id.metadata = {"url": "/{policyAssignmentId}"} + + @distributed_trace_async + async def get_by_id(self, policy_assignment_id: str, **kwargs: Any) -> _models.PolicyAssignment: + """Gets a policy assignment by ID. + + When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for + subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for + resource groups, and + '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' + for resources. + + :param policy_assignment_id: The ID of the policy assignment to get. Use the format + '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. + Required. + :type policy_assignment_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + request = build_policy_assignments_get_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_id.metadata = {"url": "/{policyAssignmentId}"} + + +class PolicySetDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2017_06_01_preview.aio.PolicyClient`'s + :attr:`policy_set_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + policy_set_definition_name: str, + parameters: _models.PolicySetDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, policy_set_definition_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, policy_set_definition_name: str, parameters: Union[_models.PolicySetDefinition, IO], **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinition type + or a IO type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinition") + + request = build_policy_set_definitions_create_or_update_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("PolicySetDefinition", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("PolicySetDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}" + } + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, policy_set_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition. + + :param policy_set_definition_name: The name of the policy set definition to delete. Required. + :type policy_set_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_set_definitions_delete_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}" + } + + @distributed_trace_async + async def get(self, policy_set_definition_name: str, **kwargs: Any) -> _models.PolicySetDefinition: + """Gets the policy set definition. + + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + request = build_policy_set_definitions_get_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}" + } + + @distributed_trace_async + async def get_built_in(self, policy_set_definition_name: str, **kwargs: Any) -> _models.PolicySetDefinition: + """Gets the built in policy set definition. + + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + request = build_policy_set_definitions_get_built_in_request( + policy_set_definition_name=policy_set_definition_name, + api_version=api_version, + template_url=self.get_built_in.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_built_in.metadata = {"url": "/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}"} + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.PolicySetDefinition"]: + """Gets all the policy set definitions for a subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_set_definitions_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions"} + + @distributed_trace + def list_built_in(self, **kwargs: Any) -> AsyncIterable["_models.PolicySetDefinition"]: + """Gets all the built in policy set definitions. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_set_definitions_list_built_in_request( + api_version=api_version, + template_url=self.list_built_in.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_built_in.metadata = {"url": "/providers/Microsoft.Authorization/policySetDefinitions"} + + @overload + async def create_or_update_at_management_group( + self, + policy_set_definition_name: str, + management_group_id: str, + parameters: _models.PolicySetDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition at management group level. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + policy_set_definition_name: str, + management_group_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition at management group level. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + policy_set_definition_name: str, + management_group_id: str, + parameters: Union[_models.PolicySetDefinition, IO], + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition at management group level. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinition type + or a IO type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinition") + + request = build_policy_set_definitions_create_or_update_at_management_group_request( + policy_set_definition_name=policy_set_definition_name, + management_group_id=management_group_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("PolicySetDefinition", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("PolicySetDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + create_or_update_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}" + } + + @distributed_trace_async + async def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, policy_set_definition_name: str, management_group_id: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition at management group level. + + :param policy_set_definition_name: The name of the policy set definition to delete. Required. + :type policy_set_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_set_definitions_delete_at_management_group_request( + policy_set_definition_name=policy_set_definition_name, + management_group_id=management_group_id, + api_version=api_version, + template_url=self.delete_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}" + } + + @distributed_trace_async + async def get_at_management_group( + self, policy_set_definition_name: str, management_group_id: str, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Gets the policy set definition at management group level. + + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + request = build_policy_set_definitions_get_at_management_group_request( + policy_set_definition_name=policy_set_definition_name, + management_group_id=management_group_id, + api_version=api_version, + template_url=self.get_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}" + } + + @distributed_trace + def list_by_management_group( + self, management_group_id: str, **kwargs: Any + ) -> AsyncIterable["_models.PolicySetDefinition"]: + """Gets all the policy set definitions for a subscription at management group. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2017-06-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2017-06-01-preview") + ) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_set_definitions_list_by_management_group_request( + management_group_id=management_group_id, + api_version=api_version, + template_url=self.list_by_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions" + } + + +class PolicyDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.v2017_06_01_preview.aio.PolicyClient`'s + :attr:`policy_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, policy_definition_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO], **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + request = build_policy_definitions_create_or_update_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_definitions_delete_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Gets the policy definition. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def get_built_in(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Gets the built in policy definition. + + :param policy_definition_name: The name of the built in policy definition to get. Required. + :type policy_definition_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_built_in_request( + policy_definition_name=policy_definition_name, + api_version=api_version, + template_url=self.get_built_in.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_built_in.metadata = {"url": "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}"} + + @overload + async def create_or_update_at_management_group( + self, + policy_definition_name: str, + management_group_id: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + policy_definition_name: str, + management_group_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy definition properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + policy_definition_name: str, + management_group_id: str, + parameters: Union[_models.PolicyDefinition, IO], + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a IO + type. Required. + :type parameters: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/json'. Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + request = build_policy_definitions_create_or_update_at_management_group_request( + policy_definition_name=policy_definition_name, + management_group_id=management_group_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, management_group_id: str, **kwargs: Any + ) -> None: + """Deletes a policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_policy_definitions_delete_at_management_group_request( + policy_definition_name=policy_definition_name, + management_group_id=management_group_id, + api_version=api_version, + template_url=self.delete_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace_async + async def get_at_management_group( + self, policy_definition_name: str, management_group_id: str, **kwargs: Any + ) -> _models.PolicyDefinition: + """Gets the policy definition at management group level. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + request = build_policy_definitions_get_at_management_group_request( + policy_definition_name=policy_definition_name, + management_group_id=management_group_id, + api_version=api_version, + template_url=self.get_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_at_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}" + } + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.PolicyDefinition"]: + """Gets all the policy definitions for a subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions"} + + @distributed_trace + def list_built_in(self, **kwargs: Any) -> AsyncIterable["_models.PolicyDefinition"]: + """Gets all the built in policy definitions. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_built_in_request( + api_version=api_version, + template_url=self.list_built_in.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_built_in.metadata = {"url": "/providers/Microsoft.Authorization/policyDefinitions"} + + @distributed_trace + def list_by_management_group( + self, management_group_id: str, **kwargs: Any + ) -> AsyncIterable["_models.PolicyDefinition"]: + """Gets all the policy definitions for a subscription at management group level. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2016-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2016-12-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_policy_definitions_list_by_management_group_request( + management_group_id=management_group_id, + api_version=api_version, + template_url=self.list_by_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions" + } diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2017_06_01_preview/aio/operations/_patch.py b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2017_06_01_preview/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dd32510333d0179c1c2d2f986b657b3247d76c --- /dev/null +++ b/pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/policy/v2017_06_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """